PHP Goto Control Structure

Saturday, February 19, 2011 2:02
Posted in category PHP Snippets, PHP Tutorials

The PHP goto operator was released in PHP 5.3. It permits you to jump from one section of code to another.

Example usage:

for( $x = 0; $x <= 1000; $x++ ) {
    if( $x == 999 ) goto finish;
}
echo "The for loop ended naturally.";

finish:
echo "Exited the loop prematurely and jumped to this location.";

The above block of code outputs ‘Exited the loop prematurely and jumped to this location.’.

While goto may seem like a very useful new operator, use it sparingly (if at all). It’s generally accepted as bad programming practice. Overuse of the goto operator can result in a very confusing program flow. If you have a large application with code jumping all over the place, it is very difficult to read and follow. Wherever possible, try to follow a structured programming approach.

PHP Namespace Example

Tuesday, February 15, 2011 5:56

Namespaces are a new feature of PHP 5.3. I may write an actual tutorial for namespaces in PHP later down the track. When it was first introduced in PHP, I wrote a small application to test the namespace functionality. I’ve attached the code.

Basically, it’s a very simple CMS that grabs and outputs content from the database.

PHP Namespace Example

PHP Image Resizer

Thursday, October 28, 2010 2:15

Here is a script that takes a regular sized image and resizes it on the fly. It is a PHP Image Resizer. It also caches the result, to save resources and execution time. It’s fairly easy to use:

1. Upload the cache.php script to your document root.
2. Create a directory called ‘cache’, CHMOD to 0777 and place a blank index.html file in there.

And that’s all we need to do. Next, we have to pass the image location to the script and the width & height. This is where we can just use URL variables:

  • f = absolute path to the image
  • w = width (in pixels)
  • h = height (in pixels)

i.e. cache.php?f=/path/to/image.jpg&w=100&h=50

If there are any other features you’ve seen in other PHP Image Resizers and think should be added, feel free to leave a comment.

For instance, to display a resized image, we would have to do something like:

<img src="http://phpduck.com/cache.php?f=/images/original_image.jpg&h=100&w=200" alt="Resized Image" />

There is also the option to crop an image. For instance, if we had an image with an aspect ratio of 4:3, and we shrunk it to a smaller size with an aspect ratio of 2:3, it would appear squashed and distorted. This is where the crop tool comes in handy; while we lose some of the image, we make sure that it at least appears normal. To crop an image, you simply have to include the ‘crop’ variable in the URL. i.e.:

<img src="http://phpduck.com/cache.php?f=/images/original_image.jpg&h=100&w=200&crop" alt="Resized Cropped Image" />

Click the following to download the php image resizer.