Category Archives: Tips & tricks

Crop images using mask on PHP

Sometimes the rectangle images are not enough from the design point view. You can crop images using the masks on Photoshop, GIMP or other graphical manipulation software.

Another way to do it is using PHP’s GD library. Conceptual steps for croping image are as follows:

  1. Create image from source image.
  2. Resize it for you needs.
  3. Create the mask. (in our case it’s ellipsis)
  4. Merge the mask and image.

Code:

<?php
 
$filename = "sapmle.jpg";
$image_s = imagecreatefromjpeg($filename);
 
$width = imagesx($image_s);
$height = imagesy($image_s);
 
// New dimensions
$newwidth = 285;
$newheight = 232;
 
// Create new image
$image = imagecreatetruecolor($newwidth, $newheight);
imagealphablending($image,true);
imagecopyresampled($image,$image_s,0,0,0,0,$newwidth,$newheight,$width,$height);
imagedestroy($image_s);
 
// Create mask
$mask = imagecreatetruecolor($width, $height);
$mask = imagecreatetruecolor($newwidth, $newheight);
 
$transparent = imagecolorallocate($mask, 255, 0, 0);
imagecolortransparent($mask, $transparent);
imagefilledellipse($mask, $newwidth/2, $newheight/2, $newwidth, $newheight, $transparent);
 
 
 
$red = imagecolorallocate($image, 0, 0, 0);
imagecopymerge($image, $mask, 0, 0, 0, 0, $newwidth, $newheight,100);
imagecolortransparent($image, $red);
imagefill($image,0,0, $red);
 
// output and free memory
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
imagedestroy($mask);
?>

The code above produces an image like this:

Installing Redmine on cPanel

Installing Redmine on cPanel will be bit harder, because it needs some modifications on server configuration. And custom modifications will be lost on regeneration of configuration files by cPanel. According instruction at http://www.redmine.org/projects/redmine/wiki/HowTo_install_Redmine_on_CentOS_5 you will need change Apache configuration manually. It’s not okay on cPanel. Also it will be conflicts with the Ruby, Rack, RoR versions which comes with cPanel.

Let’s deal with it.

First of all be sure that you have root access to your server, and Ruby on Rails is uninstalled.

Get the rubygems (1.4.2 version):

wget http://production.cf.rubygems.org/rubygems/rubygems-1.4.2.tgz
tar zxvf rubygems-1.4.2.tgz
cd rubygems-1.4.2
ruby setup.rb

Then install passenger:

gem install passenger

Download and extract redmine:

wget http://rubyforge.org/frs/download.php/75518/redmine-1.2.2.tar.gz  # GET LATEST VERSION ON RUBYFORGE
tar zxvf redmine-1.2.2.tar.gz

Install bundler:

gem install bundler

Go to redmine directory and create Gemfile and install bundle:

vi /<redmine_dir>/Gemfile
source "http://rubygems.org" 
gem "rake", "0.8.3" 
gem "rack", "1.1.0" 
gem "i18n", "0.4.2" 
gem "rubytree", "0.5.2", :require => "tree" 
gem "RedCloth", "~>4.2.3", :require => "redcloth" # for CodeRay
gem "mysql" 
gem "coderay", "~>0.9.7" 
bundle install

Create database and user for it, go to redmine directory:

cd config
mv database.yml.example database.yml

Edit database.yml file and write database credentials in production section.

Now edit the config/environment.rb file.

ENV['RAILS_ENV'] ||= 'production'

Type in the shell:

RAILS_ENV=production bundle exec rake generate_session_store
RAILS_ENV=production bundle exec rake db:migrate
RAILS_ENV=production bundle exec rake redmine:load_default_data

Make sure there were no any error messages.

Go to public/ directory:

cd public/
mv dispatch.cgi.example dispatch.cgi
mv dispatch.fcgi.example dispatch.fcgi
mv dispatch.rb.example dispatch.rb
mv htaccess.fcgi.example .htaccess

Half of the work is done.

Now we must make it available to cPanel. So cPanel uses different version of rack and RoR there will be conflicts.

Install rubyonrails for cPanel.

/scripts/installruby

It will install RoR, RubyGems, Rack etc. which not compatible with redmine. Otherwise you’ll not be able to start ruby application from cPanel. So, create application named redmine and show the path(e.x. /home/redmine/ruby_apps/redmine – but it’s not real redmine directory with you just configured, it’s better show the non-existing directory). Once application is created. You can start it.

Start by clicking Run button on cPanel.

Test it http://yoursite.com:12001. If everything is okay, so we can continue for tricks.

Now stop it.

Go to directory which you created with RoR application on cPanel. Remove all files, copy everything from configured redmine directory. Then go to rubygems directory where you downloaded 1.4.2 version.

ruby setup.rb

Go to redmine directory

gem install passenger
bundle install

Change permissions for redmine directory.

cd ..
chown -R apache:apache redmine_dir
chmod -R 755 redmine_dir

Now go to cPanel, Ruby on Rails section. Run the application. Now it’s ready on http://yoursite.com:12001. You can make it available on port 80 with htaccess.

Enjoy!

Getting thumbnail from YouTube

Getting thumbnail image of any YouTube video you need it’s video ID number. Video ID number is the 11 character string in the url and assigned to v parameter. For example video ID of this video http://www.youtube.com/watch?v=S5msjdZIoag&feature=related is S5msjdZIoag.

You can get the video ID by the URL simply with strpos() function in PHP.

function getVideoID($url) {
    // get v parameter position
    $pos = strpos($url,"?v=");
    if ($pos==false) $pos = strpos($url,"&amp;v=");
 
    if ($pos==false) return false;
 
    return substr($url,$pos+3,11);
}

The url http://i.ytimg.com/vi/S5msjdZIoag/default.jpg is the thumbnail image of the video above. As you see the S5msjdZIoag string is present in this url too. So url of thumbnail image of any video is http://i.ytimg.com/vi/<video_id>/default.jpg

function getVideoID($url) {
    // get v parameter position
    $pos = strpos($url,"?v=");
    if ($pos==false) $pos = strpos($url,"&v=");
 
    if ($pos==false) return false;
 
    return substr($url,$pos+3,11);
}
 
function getVideoThumbnail($videoId) {
 
    return "http://i.ytimg.com/vi/".$videoId."/default.jpg";
 
}
 
$url = "http://www.youtube.com/watch?v=S5msjdZIoag&feature=related";
 
$videoId = getVideoID($url);
 
echo (getVideoThumbnail($videoId));

Reference:

http://code.google.com/apis/youtube/2.0/developers_guide_protocol.html

Removing UTF8 BOM from PHP files

UTF8 Byte Order Mark (BOM) is sequence of bytes for represent the file as UTF8. The sequence is hexadecimal EF BB BF value also you can see it at the beginning of the file as ï»¿. When these symbols is used the text editor recognizes that file as UTF8.

In most cases it creates a problem for PHP programmers. When php file is interpreted these symbols sent to the output directly (because there are not inside of <?php ?> tags). If the php file modifies or sends headers, BOM is sent before the headers(as an output) and sending headers fails. Usually you see such error:

Warning: Cannot modify header information – headers already sent by (output started at /path/to/php/public_html/config.php:28) in /path/to/php/public_html/index.php on line 101

The solution is to remove the UTF8 BOM signature from the PHP files. On Notepad++ or EmEditor you can save the file without UTF8 BOM. Another method is to open the files with the editor with can’t read utf8 and remove these byte order manually.

The easiest way is bomremover tool. You can get it from http://code.google.com/p/bomremover/ .

 

#cd /path/to/php/files/
#/path/to/bomremover/bomremover.sh -r

This will recursively locate the files and remove the BOM from files.

For removing BOM from a single file:

#cd /path/to/php/files/
#/path/to/bomremover/bomremover.sh index.php

 

Reference:

Getting twitter messages on PHP

It’s usual on web sites to place a widget with twitter messages by site owner. There are many methods to get messages from Twitter. For example you can do it using Twitter API.

There is another very simple method. It’s possible to get the messages via RSS.

The page contains RSS feed of tweets by me.

http://twitter.com/statuses/user_timeline/adilaliyev.rss



On PHP you can get the contents of RSS with a help of cURL:

<?php
// create a new cURL handle
$ch = curl_init();
 
// set RSS URL
curl_setopt($ch, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/adilaliyev.rss");
 
// set additional options
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 
// get the contents
$a = curl_exec($ch);
 
echo ($a);
 
// close cURL handle
curl_close($ch);
?>

After getting the RSS feeds you can manipulate it using XML Features of PHP.

Graphic icons for buttons

Most common problem of software developers is finding good graphic icons for buttons, links or something like that.

There are many sites where you can download such icons in various sizes. One good method is searching on google. Type on search text

name_of_icon imagesize:16×16

For example:

folder imagesize:16×16

It will search for images in 16×16 pixel size. Usually in 16x16px size images are little icons for buttons or favicons of web-sites so probably you will get what you want in a results page.

Another method searching on http://findicons.com/ web site. It has nice interface and you can select different sizes of image and different file types.

The http://www.iconarchive.com/ also good source for finding icons. But it’s interface bit complicated.

http://openiconlibrary.sourceforge.net/ this is collection of public licensed graphic icons. Quantity of icons is about 10 000. Big advantage of openiconlibrary is that you can download overall package. But it has no any search system so, you will search by one.

wget as a hacker tool

Few days ago some people called himself web-programmers, created a web-site where it was online voting for the parliament in my country. It was a simple system you select your region, select the candidate and vote for him. The purpose of this system was to know approximate results of the election…

One of the sites used requests by GET method. The only limit was about IP address. So, from one IP address you vote once. Many people took the URL with the request and put it to their web sites as a iframe, img, or something else. For example:
http://namized.com/index.php?menyu=sesver&daireid=55&namizedid=74&buttson=S%C6%8FS+VER

You put this on the iframe in your page

<iframe src="http://namized.com/index.php?menyu=sesver&daireid=55&namizedid=74&buttson=S%C6%8FS+VER"></iframe>

and when your page is visited automatically it’s voted for “your” candidate.

GNU has a good tool called wget for downloading files from internet(or any other network). wget has a lot of options for performing different operations while you download the files. Most important options for “voting” purposes are –proxy, this little bash script will do your job:

while read line   
do   
    export http_proxy=$line
    wget --proxy=on "http://namized.com/index.php?menyu=sesver&daireid=55&namizedid=74&buttson=S%C6%8FS+VER"
done <proxy.list

Googling for proxy server list and copy/pasting them to proxy.list file on the current directory and then executing the script will vote for your candidate from different proxies. So, recorded IP address will be proxy IP address not yours.

Additionally if you want speed up the process by reducing your RAM and network resources you can change the script as follow:

while read line   
do   
    export http_proxy=$line
    wget --tries=1 --timeout=10 --proxy=on "http://namized.com/index.php?menyu=sesver&daireid=55&namizedid=74&buttson=S%C6%8FS+VER" &
done <proxy.list

Another web site used POST requests. wget has an option –post-data for solving this problem :)

Hmmm. Using a captcha could solve the problem…

Ignoring browser commands

I have rarely encountered such situation, but for larger projects it is certainly common problem. Assume that the script performs some queries in the database (deleting / adding / editing) and during these user presses the Stop button in your browser. By this command php script completes its work, which in our case may be fraught with violations of the integrity of the database.

This problem is resolved by function ignore_user_abort ():

ignore_user_abort (true);

… Is executed queries to the database …

ignore_user_abort (false);

Original source: http://i-novice.net/poleznye-php-tryuki/

Note: Best solution for such problems is using transaction on databases :)

fixed position on IE6

Fixed position on xhtml elements make the elements fixed at its coordinates and it is not moved when you scroll the pages. One of popular example can be facebook panel.

#elementId {
    position:fixed;
    bottom:0;
}

An example above will make the element stayed at the bottom of page.

But there is an issue on IE6 and this can be fixed via javascript. Simply get the javascript code from here and include to your page:

<script type="text/javascript" src="fixed.js"></script>

Reference:

http://www.doxdesk.com/software/js/fixed.html

Regular expressions in SQL queries

Regular expressions are useful for parsing string, matching patterns, validating etc. If we talk about strings so, I think it’s good idea using it in SQL queries.

Let we have table users:

mysql> SELECT * FROM users;
+----+-----------+----------+----------------------+
| id | first     | last     | email                |
+----+-----------+----------+----------------------+
|  1 | John      | SMITH    | jsmith@example.az    |
|  2 | Bill      | Gates    | bgates@example.ru    |
|  3 | Steve     | Jobs     | sjobs@example.de     |
|  4 | Sylvester | Stallone | stallone@example.com |
|  5 | Chuck     | Norris   | cnorris@example.net  |
|  6 | Bruce     | Lee      | blee@example1.net    |
+----+-----------+----------+----------------------+
6 rows in set (0.00 sec)

Now we want to get users whose email ends with three-letter TLD (.com,.net,.org etc). We can do this as follows:

mysql> SELECT * FROM users WHERE email LIKE '%.___';
+----+-----------+----------+----------------------+
| id | first     | last     | email                |
+----+-----------+----------+----------------------+
|  4 | Sylvester | Stallone | stallone@example.com |
|  5 | Chuck     | Norris   | cnorris@example.net  |
|  6 | Bruce     | Lee      | blee@example1.net    |
+----+-----------+----------+----------------------+
3 rows in set (0.00 sec)

Well.

What can we do, if we need get users whose email ends with digit dot three-letter TLD(blee@example1.net)? ooops.

I’ll not lie, I don’t know how to do it with ANSI SQL and I’ll use RDBMS specific functions. This example works for MySQL:

mysql> SELECT * FROM users WHERE email REGEXP '^.+[0-9]\.[a-z]{3}$';
+----+-------+------+-------------------+
| id | first | last | email             |
+----+-------+------+-------------------+
|  6 | Bruce | Lee  | blee@example1.net |
+----+-------+------+-------------------+
1 row in set (0.00 sec)

For Oracle it will as follow:

SELECT * FROM users WHERE REGEXP_LIKE(email,'^.+[0-9]\.[a-z]{3}$')

Thanks for my co-worker Mahir for the idea ;)

Reference:
http://www.oracle.com/technology/oramag/webcolumns/2003/techarticles/rischert_regexp_pt1.html
http://dev.mysql.com/doc/refman/5.1/en/regexp.html