Create Images Thumbnails And Cache Them In PHP

14 November, 2008 | PHP | No comments

Creating image thumbnails is a pretty common practice, and there are a few scripts available that allow you to do this in PHP using the GD2 library. However, they are normally overkill for what should be a simple task, so after a bit of searching and testing I found the following ImageResize class, which is taken from http://shiege.com/scripts/thumbnail/. I have modified the code to be PHP5, but if you want the PHP4 version then you can get it from the site.

class ImageResize{
  public $img;
 
  public function ImageResize($imgfile){
    //detect image format
    $this->img["format"] = ereg_replace(".*\.(.*)$","\\1",$imgfile);
    $this->img["format"] = strtoupper($this->img["format"]);
    if($this->img["format"] == "JPG" || $this->img["format"] == "JPEG"){
      //JPEG
      $this->img["format"] = "JPEG";
      $this->img["src"] = ImageCreateFromJPEG ($imgfile);
    }elseif($this->img["format"] == "PNG"){
      //PNG
      $this->img["format"] = "PNG";
      $this->img["src"] = ImageCreateFromPNG ($imgfile);
    }elseif($this->img["format"] == "GIF"){
      //GIF
      $this->img["format"] = "GIF";
      $this->img["src"] = ImageCreateFromGif($imgfile);
    }elseif($this->img["format"] == "WBMP"){
      //WBMP
      $this->img["format"] = "WBMP";
      $this->img["src"] = ImageCreateFromWBMP ($imgfile);
    }else{
      //DEFAULT
      echo "Not Supported File";
      exit();
    };
    $this->img["lebar"] = imagesx($this->img["src"]);
    $this->img["tinggi"] = imagesy($this->img["src"]);
    //default quality jpeg
    $this->img["quality"] = 75;
  }
 
  public function size_height($size = 100){
    //height
    $this->img["tinggi_thumb"] = $size;
    $this->img["lebar_thumb"] = ($this->img["tinggi_thumb"]/$this->img["tinggi"])*$this->img["lebar"];
  }
 
  public function size_width($size = 100){
    //width
    $this->img["lebar_thumb"] = $size;
    $this->img["tinggi_thumb"] = ($this->img["lebar_thumb"]/$this->img["lebar"])*$this->img["tinggi"];
  }
 
  public function size_auto($size = 100){
    //size
    if($this->img["lebar"]> = $this->img["tinggi"]){
      $this->img["lebar_thumb"] = $size;
      $this->img["tinggi_thumb"] = ($this->img["lebar_thumb"]/$this->img["lebar"])*$this->img["tinggi"];
    }else{
      $this->img["tinggi_thumb"] = $size;
      $this->img["lebar_thumb"] = ($this->img["tinggi_thumb"]/$this->img["tinggi"])*$this->img["lebar"];
    };
  }
 
  public function jpeg_quality($quality = 75){
    //jpeg quality
    $this->img["quality"] = $quality;
  }
 
  public function show(){
    //show thumb
    header("Content-Type: image/".$this->img["format"]);
 
    /* change ImageCreateTrueColor to ImageCreate if your GD not supported ImageCreateTrueColor function*/
    $this->img["des"] = ImageCreateTrueColor($this->img["lebar_thumb"],$this->img["tinggi_thumb"]);
    imagecopyresampled($this->img["des"], $this->img["src"], 0, 0, 0, 0, $this->img["lebar_thumb"], $this->img["tinggi_thumb"], $this->img["lebar"], $this->img["tinggi"]);
 
    if($this->img["format"] == "JPG" || $this->img["format"] == "JPEG"){
      //JPEG
      imageJPEG($this->img["des"],"",$this->img["quality"]);
    }elseif($this->img["format"] == "PNG"){
      //PNG
      imagePNG($this->img["des"]);
    }elseif($this->img["format"] == "GIF"){
      //GIF
      imageGIF($this->img["des"]);
    }elseif($this->img["format"] == "WBMP"){
      //WBMP
      imageWBMP($this->img["des"]);
    };
  }
 
  public function save($save = ""){
    //save thumb
    if(empty($save)){
      $save = strtolower("./thumb.".$this->img["format"]);
    }
    /* change ImageCreateTrueColor to ImageCreate if your GD not supported ImageCreateTrueColor function*/
    $this->img["des"] = ImageCreateTrueColor($this->img["lebar_thumb"],$this->img["tinggi_thumb"]);
    imagecopyresampled($this->img["des"], $this->img["src"], 0, 0, 0, 0, $this->img["lebar_thumb"], $this->img["tinggi_thumb"], $this->img["lebar"], $this->img["tinggi"]);
 
    if($this->img["format"] == "JPG" || $this->img["format"] == "JPEG"){
      //JPEG
      imageJPEG($this->img["des"],"$save",$this->img["quality"]);
    }elseif($this->img["format"] == "PNG"){
      //PNG
      imagePNG($this->img["des"],"$save");
    }elseif($this->img["format"] == "GIF"){
      //GIF
      imageGIF($this->img["des"],"$save");
    }elseif($this->img["format"] == "WBMP"){
      //WBMP
      imageWBMP($this->img["des"],"$save");
    };
  }
}

Put this into a file called class.ImageResize.php and you can use it to resize and show any image you want.

include('class.ImageResize.php');
// create ImageResize object
$originalImage = new ImageResize("anImage.jpg");
// use the show function to print this image to screen
$originalImage->show();
// use the save function to save this image to another file - leave empty to save as thumb.anImage.jpg
$originalImage->save("anotherFile.png");
// use one of the size functions to resize the image
$originalImage->size_width(120);
// save it again...
$originalImage->save("thumb_anotherFile.png");

If you want to create a simple thumbnail caching function then you can use the following code. It checks to see if the image exists and if it is older than 30 days. If it is then the file is deleted and because the file no longer exists (or if it never existed) the next part of the code where the thumbnail is created is run.

$imageName = str_replace(dirname("./images/", "" , "http://www.example.com/images/an_image.jpg");
 
if ( file_exists("./thumb_cache".$imageName) ) {
  // 2592000 = 30 days
  if ( time() - filemtime("./thumb_cache".$imageName) > 2592000 ) {
    unlink("./thumb_cache".$imageName);
  }
}
if ( !file_exists("./thumb_cache".$imageName) ) {
  include('class.ImageResize.php');
  // if cache file does not exist then create it.
  $originalImage = new ImageResize("./images/".$_result['image_path']);
  $originalImage->size_width(120);
  $originalImage->save("./thumb_cache".$imageName);
}

Creating A Simple Widget In Wordpress

13 November, 2008 | Wordpress | No comments

A widget is a little program that fits into the side menu of your site. These widgets can be moved around using the admin section of your Wordpress blog and there are quite a few to chose from with a default install.

To create a theme that supports widgets you can follow the instructions in the post creating a widget proof Wordpress theme.

You can create a widget in one of two places, either within your functions.php file of your template, or in a plugin. To get a widget to display you need to call a function called register_sidebar_widget(). This function takes two parameters, the name of the widget in the admin section, and a callback function that controls what the widget contains.

register_sidebar_widget(__('My Widget'), 'myWidgetFunction');

The callback function takes a single parameter called $args, which is used to pass in all of the parameters that are set in the register_sidebar() function call. The first thing you have to do is use the extract() function to convert the $args variable into separate variables. After this function you will have access to such variables as $before_widget, $after_widget, $before_title and $after_title.

The following is an example of a very simple widget callback function that produces a widget with a single bit of text.

function myWidgetFunction($args) {
 extract($args);
 echo $before_widget;
 echo $before_title . __('My Widget') . $after_title;
 echo '<ul><li>The contents of my widget go right here.</li></ul>';
 echo $after_widget;
}

Of course if you wanted the widget to do something more interesting, which is probably your intent, then you can replace this line of text with a loop, or function call or whatever you need.

When you visit the widgets page in the Design section of your blog admin you will now see a widget called My Widget, which you can add to the current widgets on your blog.

Finally, you might have noticed that there is no descriptive text for the widget in your admin section. To add this you have to use the wp_registered_widgets variable, which contains an array of the registered widgets. You need to reference your widget and set an option called description to set the description in your admin section.

$wp_registered_widgets[sanitize_title('My Widget')]['description'] = 'A description of your widget.';

This took me quite a while to track down, and doesn’t seem to be in any of the Wordpress codex.

Get The IP Address Of A Visitor Through PHP

12 November, 2008 | PHP | No comments

I have talked previously about getting an IP address of a visitor with PHP. The failing in using the value of $_SERVER['REMOTE_ADDR'] is that if the visitor is using a proxy then you will get the proxy IP address and not the visitors real IP address.

This function works by going through any variables in the $_SERVER array that might exist that would contain information to do with IP addresses. If they are all empty then the function finally looks at $_SERVER['REMOTE_ADDR'] value and returns this as a default.

function getRealIpAddr(){
 if ( !empty($_SERVER['HTTP_CLIENT_IP']) ) {
  //check ip from share internet
  $ip = $_SERVER['HTTP_CLIENT_IP'];
 } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
  //to check ip is pass from proxy
  $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
 } else {
  $ip = $_SERVER['REMOTE_ADDR'];
 }
 return $ip;
}

To run this function just call it.

echo getRealIpAddr();

This function was originally found here.

Edit Any Web Page With JavaScript

11 November, 2008 | JavaScript | No comments

If you want to directly edit any page that you are looking at then copy and paste the following JavaScript into your address bar.

javascript:document.body.contentEditable='true' document.designMode='on' void 0

I have created a handy little bookmarklet that you can use to do the same thing.

Edit

This code has been tested in IE7, Firefox and Chrome and works well in all three.

Of course, it goes without saying that you don’t actually edit the site, just the content that you see on the screen. Hitting refresh will remove any editing that you have done. This little tool is ideal if you want to see what different content would look like on the page without having to edit HTML. It can also be used to create spoof pages with false content.

Moving Files In PHP

11 November, 2008 | PHP | No comments

I have been asked a couple of times recently if PHP has a function that will move a file, so I thought I would put the solution here.

PHP has a function called rename() which can be used to rename a file, but because of the way it works it can be used to move files. Let’s say that you wanted to rename a file called test.txt to test_back.txt, this can be accomplished by doing the following.

rename("test.txt", "test_back.txt");

However, if you want to move the file from one directory to another you can do the following.

rename("test.txt", "backups/test_back.txt");

The return value of rename() is boolean that tells you if the rename was successful or not, this can be used to error check like this.

if ( !rename("test.txt", "backups/test_back.txt") ) {
 // rename not successful, try another way
}

Be aware that if you try the following:

rename("test.txt", "test.txt");

The function will return true.

To rename a directory you should do the following:

rename("directory/directoryold","directory/directorynew");

Note the absence of the trailing slash on the directory name, PHP will give an error if this slash is added.