Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Image Generation Using PHP

alt="Image Generation Using PHP"
title="A Sample Image Generated Using Our Script"
src="http://one.arvind.googlepages.com/php_image_generation.png">



In one of the previous posts about href="http://learning-computer-programming.blogspot.com/2009/03/how-captcha-works-and-simple-script-in.html">CAPTCHA
Image Generation
we made use of PHP’s image generation functions
but didn’t discuss about them. So, if you had any problems or just want
to know more, read on.


Creating and outputting images from PHP is very simple and easy. And
since PHP supports images in a number of different formats you can very
easily generate images in various formats such as JPEG, PNG, GIF etc.
Generating  images involves the following steps:




  1. Creating a canvas.




  2. Drawing




  3. Outputting the image.




Now, let’s look at each of the steps in detail.


Creating a Canvas


Creating a canvas is very easy, just use the following function:


style="color: rgb(0, 0, 187);">resource ImageCreateTrueColor style="color: rgb(0, 119, 0);">( style="color: rgb(0, 0, 187);">int $width style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $height style="color: rgb(0, 119, 0);">)style="color: rgb(0, 119, 0);">
style="color: rgb(0, 119, 0);">style="color: rgb(0, 0, 187);">

The capitalization doesn’t matter as with any function in PHP.


If you want your canvas to have some background color (default is
black) you can use the following function:


style="color: rgb(0, 0, 187);">bool ImageFill style="color: rgb(0, 119, 0);">( style="color: rgb(0, 0, 187);">resource $image style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $x style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $y style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $color style="color: rgb(0, 119, 0);">)

Where color is to be first allocate using the following function:


style="color: rgb(0, 0, 187);">int ImageColorAllocate style="color: rgb(0, 119, 0);">( style="color: rgb(0, 0, 187);">resource $image style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $red style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $green style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $blue style="color: rgb(0, 119, 0);">)

You can also use an existing image as base canvas for your new
image,
in that case create your image using the following function:


style="color: rgb(0, 0, 187);">resource ImageCreateFromJPEG style="color: rgb(0, 119, 0);">( style="color: rgb(0, 0, 187);">string $filename style="color: rgb(0, 119, 0);">)

Images in other format can also be used, for PNG →  style="color: rgb(0, 0, 187);">ImageCreateFromPNG style="color: rgb(0, 119, 0);">(), GIF → style="color: rgb(0, 0, 187);">ImageCreateFromGIF style="color: rgb(0, 119, 0);">().


Drawing


After having set up the canvas, let’s draw something on it, say, a
rectangle. The rectangle drawing function with its argument list is:


style="color: rgb(0, 0, 187);">bool ImageRectangle style="color: rgb(0, 119, 0);">( style="color: rgb(0, 0, 187);">resource $image style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $x1 style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $y1 style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $x2 style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $y2 style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $color style="color: rgb(0, 119, 0);">)

For allocating color use the style="color: rgb(0, 0, 187);">ImageColorAllocatestyle="color: rgb(0, 119, 0);">() function.


The following will create a square of size 10px X 10px having a blue
border:


style="color: rgb(0, 0, 187);">$img style="color: rgb(0, 119, 0);">= style="color: rgb(0, 0, 187);">ImageCreateTrueColorstyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">20style="color: rgb(0, 119, 0);">, 20style="color: rgb(0, 0, 187);">style="color: rgb(0, 119, 0);">);
style="color: rgb(0, 0, 0);">$blue style="color: rgb(0, 119, 0);">= style="color: rgb(0, 0, 187);">ImageColorAllocatestyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$imgstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">255style="color: rgb(0, 119, 0);">);
style="color: rgb(0, 119, 0);">style="color: rgb(255, 128, 0);">style="color: rgb(0, 0, 187);">ImageRectanglestyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$imgstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">10style="color: rgb(0, 119, 0);">style="color: rgb(0, 0, 187);">style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">10style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">$bluestyle="color: rgb(0, 119, 0);">);

You can browse the complete list of href="http://in.php.net/manual/en/ref.image.php">drawing (GD)
functions in PHP
here
.


Some of the common ones are:



  1. bool ImageLine style="color: rgb(0, 119, 0);">( style="color: rgb(0, 0, 187);">resource $image style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $x1 style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $y1 style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $x2 style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $y2 style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $color )

  2. style="color: rgb(0, 0, 187);">bool ImageEllipse style="color: rgb(0, 119, 0);">( style="color: rgb(0, 0, 187);">resource $image style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $cx style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $cy style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $width style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $height style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $color style="color: rgb(0, 119, 0);">) style="color: rgb(0, 0, 187);">

  3. style="color: rgb(0, 0, 187);">bool ImageArc style="color: rgb(0, 119, 0);">( style="color: rgb(0, 0, 187);">resource $image style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $cx style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $cy style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $width style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $height style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $start style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $end style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $color style="color: rgb(0, 119, 0);">)




I think we should also discuss a little about one function, to draw
text on out image, it’s called the style="color: rgb(0, 0, 187);">ImageStringstyle="color: rgb(0, 119, 0);">() function having the
following form:


style="color: rgb(0, 0, 187);">bool ImageString style="color: rgb(0, 119, 0);">( style="color: rgb(0, 0, 187);">resource $image style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $font style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $x style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $y style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">string $string style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">int $color style="color: rgb(0, 119, 0);">)style="color: rgb(0, 0, 187);">
style="color: rgb(0, 119, 0);">

Example:


style="color: rgb(0, 0, 187);">$img style="color: rgb(0, 119, 0);">= style="color: rgb(0, 0, 187);">ImageCreateTrueColorstyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">100style="color: rgb(0, 119, 0);">, 100style="color: rgb(0, 0, 187);">style="color: rgb(0, 119, 0);">);
style="color: rgb(0, 0, 0);">$red style="color: rgb(0, 119, 0);">= style="color: rgb(0, 0, 187);">ImageColorAllocatestyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$imgstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">255style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">);
style="color: rgb(0, 0, 0);">ImageStringstyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$imgstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">7style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">10style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">style="color: rgb(0, 119, 0);">style="color: rgb(0, 0, 187);">style="color: rgb(0, 119, 0);">style="color: rgb(0, 0, 187);">10style="color: rgb(0, 119, 0);">, style="color: rgb(221, 0, 0);">'Text'style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">$redstyle="color: rgb(0, 119, 0);">);
style="color: rgb(0, 0, 187);">ImageStringstyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$imgstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">5style="color: rgb(0, 119, 0);">, style="color: rgb(0, 119, 0);">style="color: rgb(0, 0, 187);">10style="color: rgb(0, 119, 0);">,style="color: rgb(0, 119, 0);"> style="color: rgb(0, 0, 187);">30style="color: rgb(0, 119, 0);">, style="color: rgb(221, 0, 0);">'Smaller Text'style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">$redstyle="color: rgb(0, 119, 0);">);



The above lines will draw two string of text and the first one will
have a bigger font size. Higher number fonts (for $font)
are bigger.


All done,now we have a completed image that just needs to be sent to
the browser. For this we first need to tell the browser what type of
content we’re going to send and the data (image) itself. The following
two lines will do this:


style="color: rgb(0, 0, 187);">headerstyle="color: rgb(0, 119, 0);">(style="color: rgb(221, 0, 0);">'Content-Type: image/png'style="color: rgb(0, 119, 0);">);
style="color: rgb(0, 0, 187);">ImagePNGstyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$imgstyle="color: rgb(0, 119, 0);">);

Similarly you can output image in other formats also, just replace style="color: rgb(0, 0, 187);">ImageJPEGstyle="color: rgb(0, 0, 187);"> with style="color: rgb(0, 0, 187);">ImageGIF or style="color: rgb(0, 0, 187);">ImagePNG etc. and the content-type
header to image/gif or image/png
accordingly.


After having output the image there is one more thing we should take
care of-freeing up the resources. You know images can take up
significant amount of resources which may affect the server and other
scripts running on it, so always use the following function:


style="color: rgb(0, 0, 187);">bool ImageDestroy style="color: rgb(0, 119, 0);">( style="color: rgb(0, 0, 187);">resource $image style="color: rgb(0, 119, 0);">)

The following example code illustrates all, what we have learnt:


style="color: rgb(0, 0, 187);"><?
style="color: rgb(255, 128, 0);">/********************************************************
 * DESCRIPTION: Exmple program to illustrate            *
 *              image generation using PHP.             *
 * AUTHOR:      Arvind Gupta                            *
 *              (http://www.arvindgupta.co.in)          *
 * DATE:        21-Mar-09                               *
 * WEBSITE:                                             *
 * http://learning-computer-programming.blogspot.com/   *
 ********************************************************/
// Set width and height
style="color: rgb(0, 0, 187);">$width style="color: rgb(0, 119, 0);">= style="color: rgb(0, 0, 187);">200style="color: rgb(0, 119, 0);">;
style="color: rgb(0, 0, 187);">$heightstyle="color: rgb(0, 119, 0);">= style="color: rgb(0, 0, 187);">200style="color: rgb(0, 119, 0);">;

style="color: rgb(255, 128, 0);">// Create canvas
style="color: rgb(0, 0, 187);">$img style="color: rgb(0, 119, 0);">= style="color: rgb(0, 0, 187);">ImageCreateTrueColorstyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$widthstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">$heightstyle="color: rgb(0, 119, 0);">);

style="color: rgb(255, 128, 0);">// Allocate colors
style="color: rgb(0, 0, 187);">$gray style="color: rgb(0, 119, 0);">= style="color: rgb(0, 0, 187);">ImageColorAllocatestyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$imgstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">200style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">200style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">200style="color: rgb(0, 119, 0);">);
style="color: rgb(0, 0, 187);">$red style="color: rgb(0, 119, 0);">= style="color: rgb(0, 0, 187);">ImageColorAllocatestyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$imgstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">255style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">);
style="color: rgb(0, 0, 187);">$green style="color: rgb(0, 119, 0);">= style="color: rgb(0, 0, 187);">ImageColorAllocatestyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$imgstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">255style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">);
style="color: rgb(0, 0, 187);">$blue style="color: rgb(0, 119, 0);">= style="color: rgb(0, 0, 187);">ImageColorAllocatestyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$imgstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">255style="color: rgb(0, 119, 0);">);

style="color: rgb(255, 128, 0);">// Fill background color
style="color: rgb(0, 0, 187);">ImageFillstyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$imgstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">$graystyle="color: rgb(0, 119, 0);">);

style="color: rgb(255, 128, 0);">// Draw
style="color: rgb(0, 0, 187);">ImageRectanglestyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$imgstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">5style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">5style="color: rgb(0, 119, 0);">, (style="color: rgb(0, 0, 187);">$width style="color: rgb(0, 119, 0);">- style="color: rgb(0, 0, 187);">5style="color: rgb(0, 119, 0);">), (style="color: rgb(0, 0, 187);">$height style="color: rgb(0, 119, 0);">- style="color: rgb(0, 0, 187);">5style="color: rgb(0, 119, 0);">), style="color: rgb(0, 0, 187);">$redstyle="color: rgb(0, 119, 0);">);
style="color: rgb(0, 0, 187);">ImageLinestyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$imgstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">5style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">5 style="color: rgb(0, 119, 0);">, (style="color: rgb(0, 0, 187);">$width style="color: rgb(0, 119, 0);">- style="color: rgb(0, 0, 187);">5style="color: rgb(0, 119, 0);">), (style="color: rgb(0, 0, 187);">$height style="color: rgb(0, 119, 0);">- style="color: rgb(0, 0, 187);">5style="color: rgb(0, 119, 0);">), style="color: rgb(0, 0, 187);">$redstyle="color: rgb(0, 119, 0);">);
style="color: rgb(0, 0, 187);">ImageEllipsestyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$imgstyle="color: rgb(0, 119, 0);">, (style="color: rgb(0, 0, 187);">$width style="color: rgb(0, 119, 0);">/ style="color: rgb(0, 0, 187);">2style="color: rgb(0, 119, 0);">), (style="color: rgb(0, 0, 187);">$height style="color: rgb(0, 119, 0);">/ style="color: rgb(0, 0, 187);">2style="color: rgb(0, 119, 0);">), (style="color: rgb(0, 0, 187);">$width style="color: rgb(0, 119, 0);">- style="color: rgb(0, 0, 187);">10style="color: rgb(0, 119, 0);">), (style="color: rgb(0, 0, 187);">$height style="color: rgb(0, 119, 0);">- style="color: rgb(0, 0, 187);">10style="color: rgb(0, 119, 0);">), style="color: rgb(0, 0, 187);">$greenstyle="color: rgb(0, 119, 0);">);
style="color: rgb(0, 0, 187);">ImageArcstyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$imgstyle="color: rgb(0, 119, 0);">, (style="color: rgb(0, 0, 187);">$width style="color: rgb(0, 119, 0);">/ style="color: rgb(0, 0, 187);">2style="color: rgb(0, 119, 0);">), (style="color: rgb(0, 0, 187);">$height style="color: rgb(0, 119, 0);">/ style="color: rgb(0, 0, 187);">2style="color: rgb(0, 119, 0);">), (style="color: rgb(0, 0, 187);">$width style="color: rgb(0, 119, 0);">- style="color: rgb(0, 0, 187);">40style="color: rgb(0, 119, 0);">), (style="color: rgb(0, 0, 187);">$height style="color: rgb(0, 119, 0);">- style="color: rgb(0, 0, 187);">40style="color: rgb(0, 119, 0);">), style="color: rgb(0, 0, 187);">180 style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">360style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">$bluestyle="color: rgb(0, 119, 0);">);
style="color: rgb(0, 0, 187);">ImageArcstyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$imgstyle="color: rgb(0, 119, 0);">, (style="color: rgb(0, 0, 187);">$width style="color: rgb(0, 119, 0);">/ style="color: rgb(0, 0, 187);">2style="color: rgb(0, 119, 0);">), (style="color: rgb(0, 0, 187);">$height style="color: rgb(0, 119, 0);">/ style="color: rgb(0, 0, 187);">2style="color: rgb(0, 119, 0);">), (style="color: rgb(0, 0, 187);">$width style="color: rgb(0, 119, 0);">- style="color: rgb(0, 0, 187);">60style="color: rgb(0, 119, 0);">), (style="color: rgb(0, 0, 187);">$height style="color: rgb(0, 119, 0);">- style="color: rgb(0, 0, 187);">60style="color: rgb(0, 119, 0);">), style="color: rgb(0, 0, 187);">0 style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">180style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">$greenstyle="color: rgb(0, 119, 0);">);
style="color: rgb(0, 0, 187);">ImageStringstyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$imgstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">7style="color: rgb(0, 119, 0);">, (style="color: rgb(0, 0, 187);">$width style="color: rgb(0, 119, 0);">/ style="color: rgb(0, 0, 187);">2style="color: rgb(0, 119, 0);">) - style="color: rgb(0, 0, 187);">50style="color: rgb(0, 119, 0);">, (style="color: rgb(0, 0, 187);">$height style="color: rgb(0, 119, 0);">/ style="color: rgb(0, 0, 187);">2style="color: rgb(0, 119, 0);">) - style="color: rgb(0, 0, 187);">10style="color: rgb(0, 119, 0);">, style="color: rgb(221, 0, 0);">'Image Created'style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">$redstyle="color: rgb(0, 119, 0);">);
style="color: rgb(0, 0, 187);">ImageStringstyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$imgstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">7style="color: rgb(0, 119, 0);">, (style="color: rgb(0, 0, 187);">$width style="color: rgb(0, 119, 0);">/ style="color: rgb(0, 0, 187);">2style="color: rgb(0, 119, 0);">) - style="color: rgb(0, 0, 187);">30style="color: rgb(0, 119, 0);">, (style="color: rgb(0, 0, 187);">$height style="color: rgb(0, 119, 0);">/ style="color: rgb(0, 0, 187);">2style="color: rgb(0, 119, 0);">) + style="color: rgb(0, 0, 187);">10style="color: rgb(0, 119, 0);">, style="color: rgb(221, 0, 0);">'Using PHP'style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">$greenstyle="color: rgb(0, 119, 0);">);

style="color: rgb(255, 128, 0);">// Output
style="color: rgb(0, 0, 187);">headerstyle="color: rgb(0, 119, 0);">(style="color: rgb(221, 0, 0);">'Content-Type: image/png'style="color: rgb(0, 119, 0);">);
style="color: rgb(0, 0, 187);">ImagePNGstyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$imgstyle="color: rgb(0, 119, 0);">);

style="color: rgb(255, 128, 0);">// Free-Up
style="color: rgb(0, 0, 187);">ImageDestroystyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$imgstyle="color: rgb(0, 119, 0);">);
style="color: rgb(0, 0, 187);">?>


NOTE: You need to enable the “gd2” extension from “php.ini” for all
this to work. See style="font-style: italic;"
href="http://in.php.net/manual/en/image.setup.php">Installing/Configuring
Image Support in PHP for more information.


Okay, end of this post. Keep checking back for more.

How CAPTCHA Works? And a Simple Script in PHP

[For
this post I'm
presuming that you
are familiar with CAPTCHA, if not please read this style="font-style: italic;" href="http://en.wikipedia.org/wiki/Captcha"
target="_blank">Introduction
to CAPTCHA]


src="http://one.arvind.googlepages.com/generated_captcha.png"
alt="CAPTCHA Image Generated by Our Script"
title="CAPTCHA Image Generated by Our Script" height="53" width="150">Today
we are going to see
how CAPTCHA
(Completely Automated Public
Turing test to tell Computers
and Humans Apart) works and style="font-style: italic;"
href="http://computer.howstuffworks.com/captcha.htm" target="_blank">how
it minimizes automatic sign-up
of
formhref="http://computer.howstuffworks.com/captcha.htm" target="_blank">s.
We will also be creating a
simple CAPTCHA script in
PHP to illustrate this.


Basically CAPTCHA works in
the
following manner:




  1. Create Random Value:
    Some random string is generated, random values are often hard to guess
    and predict.




  2. Generate an Image:
    Images are used as these are generally a lot harder to read for
    computers while being nice and readable to humans. This is also the
    most important step as simple text in images can be read (and CAPTCHA
    cracked) quite easily. To make it difficult for them, developers employ
    different techniques so that the text in the image becomes hard to read
    for computers. Some create zig-zag lines for background while others
    twist-and-turn individual characters in the image. Possibilities are
    many and new techniques are being developed all the time as crackers
    are always into finding ways to break them.




  3. Store it: The random
    string generated (which is also in the image) is stored for matching
    the user input. The easiest way to do so is to use the style="font-style: italic;" href="http://in.php.net/session"
    target="_blank">Session
    variables.




  4. Matching: After the
    above step, the CAPTCHA image is generated and shown on some form which
    we want to protect from being abused. The users fills in the form along
    with the CAPTCHA text and submits it. Now we have the following:




    1. All submitted form
      data.




    2. CAPTCHA string
      (from form), input by user.




    3. CAPTCHA string
      (real one, generated by us), from session variable. Session variable is
      generally used as it can keep stored values across page requests. Here,
      we needed to preserve stored values from one page (form page) to
      another (action page-that receives form data).






  5. If both match, it's
    okay otherwise not, in that case we can give the user a message that
    the CAPTCHA they had entered was wrong and their form could not be
    submitted. You could also ask them to verify it again.




The following image might
illustrates
this better:


src="http://one.arvind.googlepages.com/captch_generation_and_matching_STEPS.png"
alt="CAPTCHA Generation and Matching" align="middle" height="636"
width="417">

How CAPTCHA is Generated and Matched


From the above image it's
quite clear
that when someone requests the form page, the CAPTCHA text is
generated and sent back to requesting user, but only in the form of
an image. If the requester is a human he'd not have much difficulty
reading the image and inputting the text when asked but if it's a
bot it might face difficulties guessing whats in the image. In the
next step when we match the string generated and the one the user had
input, we can restrict automated form submissions.


The following is the code that does this, it'll just output
the CAPTCHA image to the browser when the script is requested:


style="color: rgb(0, 0, 187);"><?php
style="color: rgb(255, 128, 0);">/********************************************************
 * File:        captcha.php                             *
 * Author:      Arvind Gupta (www.arvindgupta.co.in)    *
 * Date:        12-Mar-2009                             *
 * Description: This file can be embedded as image      *
 *              to show CAPTCHA/                        *
 ********************************************************/

// The number of characters you
// want your CAPTCHA text to have
style="color: rgb(0, 0, 187);">definestyle="color: rgb(0, 119, 0);">(style="color: rgb(221, 0, 0);">'CAPTCHA_STRENGTH'style="color: rgb(0, 119, 0);">,style="color: rgb(0, 0, 187);"> 5style="color: rgb(0, 119, 0);">);

style="color: rgb(255, 128, 0);">/****************************
 *        INITIALISE        *
 ****************************/
// Tell PHP we're going to use
// Session vars
style="color: rgb(0, 0, 187);">session_startstyle="color: rgb(0, 119, 0);">();

style="color: rgb(255, 128, 0);">// Md5 to generate the random string
style="color: rgb(0, 0, 187);">$random_str style="color: rgb(0, 119, 0);">= style="color: rgb(0, 0, 187);">md5style="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">microtimestyle="color: rgb(0, 119, 0);">());

style="color: rgb(255, 128, 0);">// Trim required number of characters
style="color: rgb(0, 0, 187);">$captcha_str style="color: rgb(0, 119, 0);">= style="color: rgb(0, 0, 187);">substrstyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$random_strstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">CAPTCHA_STRENGTHstyle="color: rgb(0, 119, 0);">);

style="color: rgb(255, 128, 0);">// Allocate new image
style="color: rgb(0, 0, 187);">$width style="color: rgb(0, 119, 0);">= (style="color: rgb(0, 0, 187);">CAPTCHA_STRENGTHstyle="color: rgb(0, 119, 0);"> * style="color: rgb(0, 0, 187);">10style="color: rgb(0, 119, 0);">)+style="color: rgb(0, 0, 187);">10style="color: rgb(0, 119, 0);">;
style="color: rgb(0, 0, 187);">$height style="color: rgb(0, 119, 0);">= style="color: rgb(0, 0, 187);">20style="color: rgb(0, 119, 0);">;

style="color: rgb(0, 0, 187);">$captcha_img style="color: rgb(0, 119, 0);">=style="color: rgb(0, 0, 187);">ImageCreatestyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$widthstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">$heightstyle="color: rgb(0, 119, 0);">);

style="color: rgb(255, 128, 0);">// ALLOCATE COLORS
// Background color-black
style="color: rgb(0, 0, 187);">$back_color style="color: rgb(0, 119, 0);">= style="color: rgb(0, 0, 187);">ImageColorAllocatestyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$captcha_imgstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">);

style="color: rgb(255, 128, 0);">// Text color-white
style="color: rgb(0, 0, 187);">$text_color style="color: rgb(0, 119, 0);">= style="color: rgb(0, 0, 187);">ImageColorAllocatestyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$captcha_imgstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">255style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">255style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">255style="color: rgb(0, 119, 0);">);

style="color: rgb(255, 128, 0);">// Line color-red
style="color: rgb(0, 0, 187);">$line_color style="color: rgb(0, 119, 0);">= style="color: rgb(0, 0, 187);">ImageColorAllocatestyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$captcha_imgstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">255style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">);

style="color: rgb(255, 128, 0);">/****************************
 *     DRAW BACKGROUND &    *
 *           LINES          *
 ****************************/
// Fill background color
style="color: rgb(0, 0, 187);">ImageFillstyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$captcha_imgstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">$back_colorstyle="color: rgb(0, 119, 0);">);

style="color: rgb(255, 128, 0);">// Draw lines accross the x-axis
style="color: rgb(0, 119, 0);">for(style="color: rgb(0, 0, 187);">$i style="color: rgb(0, 119, 0);">=style="color: rgb(0, 0, 187);"> 0style="color: rgb(0, 119, 0);">; style="color: rgb(0, 0, 187);">$i style="color: rgb(0, 119, 0);"><
style="color: rgb(0, 0, 0);">$widthstyle="color: rgb(0, 0, 0);">style="color: rgb(0, 119, 0);">;style="color: rgb(0, 0, 187);"> $istyle="color: rgb(0, 119, 0);"> +=style="color: rgb(0, 0, 187);"> 5style="color: rgb(0, 119, 0);">)
    style="color: rgb(0, 0, 187);">ImageLinestyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$captcha_imgstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">$istyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">$istyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">20style="color: rgb(0, 119, 0);">,style="color: rgb(0, 0, 187);"> $line_colorstyle="color: rgb(0, 119, 0);">);

style="color: rgb(255, 128, 0);">// Draw lines accross the y-axis
style="color: rgb(0, 119, 0);">for(style="color: rgb(0, 0, 187);">$i style="color: rgb(0, 119, 0);">= style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">; style="color: rgb(0, 0, 187);">$istyle="color: rgb(0, 119, 0);"> < style="color: rgb(0, 0, 187);">20style="color: rgb(0, 119, 0);">;style="color: rgb(0, 0, 187);"> $istyle="color: rgb(0, 119, 0);"> += style="color: rgb(0, 0, 187);">5style="color: rgb(0, 119, 0);">)
    style="color: rgb(0, 0, 187);">ImageLinestyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$captcha_imgstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">0style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">$istyle="color: rgb(0, 119, 0);">,
style="color: rgb(0, 0, 0);">$widthstyle="color: rgb(0, 0, 0);">style="color: rgb(0, 0, 187);">style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">$i style="color: rgb(0, 119, 0);">,style="color: rgb(0, 0, 187);"> $line_colorstyle="color: rgb(0, 119, 0);">);

style="color: rgb(255, 128, 0);">/****************************
 *      DRAW AND OUTPUT     *
 *          IMAGE           *
 ****************************/
// Draw the random string
style="color: rgb(0, 0, 187);">ImageStringstyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$captcha_imgstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">5style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">5style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">2style="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">$captcha_strstyle="color: rgb(0, 119, 0);">, style="color: rgb(0, 0, 187);">$text_colorstyle="color: rgb(0, 119, 0);">);

style="color: rgb(255, 128, 0);">// Carry the data (KEY) through session
style="color: rgb(0, 0, 187);">$_SESSIONstyle="color: rgb(0, 119, 0);">[style="color: rgb(221, 0, 0);">'key'style="color: rgb(0, 119, 0);">] = style="color: rgb(0, 0, 187);">$captcha_strstyle="color: rgb(0, 119, 0);">;

style="color: rgb(255, 128, 0);">// Send data type
style="color: rgb(0, 0, 187);">headerstyle="color: rgb(0, 119, 0);">(style="color: rgb(221, 0, 0);">"Content-type: image/jpeg"style="color: rgb(0, 119, 0);">);

style="color: rgb(255, 128, 0);">// Output image to browser
style="color: rgb(0, 0, 187);">ImageJPEGstyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$captcha_imgstyle="color: rgb(0, 119, 0);">);

style="color: rgb(255, 128, 0);">// Free-Up resources
style="color: rgb(0, 0, 187);">ImageDestroystyle="color: rgb(0, 119, 0);">(style="color: rgb(0, 0, 187);">$captcha_imgstyle="color: rgb(0, 119, 0);">);
style="color: rgb(0, 0, 187);">?>

Okay, this it for this, in
the next one
we'll integrate this CAPTCHA script into one form and see how it
works. Till then goodbye!

Geany - A Good Web Development Editor (IDE)

href="http://geany.org/"> style="border: 0px solid ; width: 400px; height: 287px;"
alt="Geany Version 0.16" title="Screenshot of Geany"
src="http://one.arvind.googlepages.com/geany_screenshot.jpg">


href="http://geany.org/" target="_blank">Geany
Homepage


Last year I finally made a switch to GNU/Linux as my operating
system and had been in search of a good editor for my web development.
In Windows I used Dreamweaver for the purpose and was quite happy with
it. It could can easily highlight PHP, HTML, JavaScript and other codes
of some other languages related to web. It can also do some
Auto-Completion – a feature I think is a must-have. I also liked the
fact that it (version MX) was reasonably light on system resources.


When I switched to Linux, I tried Bluefish, Komodo Edit,
Netbeans IDE. Bluefish (ver 1.0.7) had  a  bad syntax
highlighting feature besides other things I found to be quite irritable
(working with PHP files, at least). Komodo Edit and Netbeans stood out
especially Komodo Edit, in terms of functionality, usability and other
small-small things. But still these were not what I was looking for. I
wanted something good in terms of functionality but at the same time
light on resources (Komodo Edit took about 15 seconds to load). I
wanted something that had a good balance between features and memory
footprint.


Geany is small (source package is about 2.2 MB), light on
resources and at the same time loaded with functionality and ease of
use for the size. Geany does not have all the features of a
full-fledged IDE (like for example Komodo Edit) but it has got many of
the important ons. And it's not just PHP and web development that you
can use it for, it has support for a good number of languages
(programming, scripting etc). But as I've only used it for web
development, I'm strictly talking in that context throughout.


Here are some of the features I find very helpful:




  1. AutoComplete: For functions(inbuilt as well as
    user-defined), variables, classes etc. Inbuilt functions are shown with
    their argument list-very useful. And there's but only a few functions I
    couldn't find in its database. Just type in a few characters and it
    shows a nice drop-down list of suggestions, select one and it shows the
    function's parameters list and their types. TIP: By default you need to
    type in at least three characters for it to give you suggestions for
    AutoComplete(ion) but it can be changes from
    Edit-> Preferences-> Edit(Side-Tab)->
    Completions(Tab).
    I personally have set it to be 1.


    style="width: 237px; height: 214px;"
    alt="Geany: Auto-Complete Feature"
    src="http://one.arvind.googlepages.com/auto_complete_feature.jpg">



  2. Compile and Make: You can't “make” a PHP script but
    compile is damn good a feature. Now forget refreshing the browser.
    NOTE: Can only check syntax errors.


    style="width: 311px; height: 75px;" alt="Geany: Compile Feature"
    src="http://one.arvind.googlepages.com/compile_feature.jpg"
    align="middle">



  3. Code-folding: Another
    useful feature especially for
    lengthy scripts.



    alt="Geany: Code Folding"
    src="http://one.arvind.googlepages.com/code_folding.png">



  4. Auto-Closing: Can close (X)HTML tags, parenthesis, curly
    braces, quotes etc. for you. Check
    Edit->Preferences->Edit(Side-Tab)->Completions(Tab)
    for settings.




  5. Sidebar: These are many tabs in the sidebar but one of
    them particularly stands ot. The one which displays “Symbols” in the
    document-variables, functions, classes, objects, constants tec. This
    one reminds me of the commercial IDEs such as Visual Studio. Just click
    on something to find its declaration.


    style="width: 232px; height: 401px;" alt="Geany: Sidebar"
    src="http://one.arvind.googlepages.com/geany_sidebar.jpg">



  6. Sessions: Just like Firefox can restore sessions of open
    tabs(websites), Geany can restore session of files. If I'm working on,
    say, ten files and I decide to go take a bath. I can close and shutdown
    my PC because Geany will open all the files for me the next time I run
    it. Great!




  7. Pre-defined Comments: Whether you want to insert copyright
    note or license information or just function information. Just right
    click and and got to “Insert Comments” menu, you have them just a click
    away! There also exist a  feature for inserting current date
    and time, for that go to “Insert Date” from the right -click menu.
    Useful!


    style="width: 375px; height: 131px;"
    alt="Geany: Pre-Defined Comments"
    src="http://one.arvind.googlepages.com/pre_defined_comments.jpg">




  8. Windows Version: Don't want to switch to Linux yet! No
    problem! Just download the windows version (needs GTK libraries
    installed)




  9. In spite so many useful features there is one more thing I
    expect Geany to do – better support for HTML files. Look, PHP and HTML
    go hand-in-hand and I'd have loved to have HTML preview feature like
    Dreamweaver has. We often embed PHP in HTML pages and Dreamweaver works
    perfectly well for these kind of pages. This is where I miss my old
    Dreamweaver the most.  I'm not saying this is Geany's
    short-coming as it's designed not just for web development, but when
    you do web development you'll  feel it's missing.




Some might wonder why I'm always mentioning Dreamweaver. This
is because unlike some of the editors I've used, it isn't just
restricted to HTML pages-it can handle dynamic content as well. Web
development isn't just HTML or PHP or ASP, it's a mix which Dreamweaver
handles quite well. It's a great HTML editor as well as it's a
quite-great PHP editor, this is what I love about it.


style="border: 3px dashed rgb(0, 0, 255); padding: 20px; margin-right: 50px; margin-left: 50px; text-align: center;"> href="http://geany.org/" target="_blank">Geany
Homepage



target="_blank">Geany
Download Page

Generating XHTML MP (WAP 2.0) Pages From PHP

alt="XHTML Mp Webpage Generation Using PHP"
title="XHTML MP (WAP 2.0) Webpage on a Cellphone"
src="http://one.arvind.googlepages.com/xhtml_mp_wap_site.jpg">Maybe
you guys know that I've been working on a service called
MyWapBlog.com which lets peoples create/manage mobile blogs using their
mobile phones. In the course of the development I've learnt great deal
about mobile websites and their dynamic generation, and I'm sharing a
bit of it here in this post.


How do you generate dynamic (X)HTML Pages using PHP? Simple:



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"  dir="ltr">
<head>
<title>Sometitle</title>
</head>
<body>
<h1>Hello</h1>
<p> style="color: rgb(0, 0, 187);"><?php 
style="color: rgb(0, 119, 0);">echo  style="color: rgb(0, 0, 187);">date style="color: rgb(0, 119, 0);">( style="color: rgb(221, 0, 0);">'h:i A, j-M-y' style="color: rgb(0, 119, 0);">);  style="color: rgb(0, 0, 187);">?></p>
</body>
</html>

And if you look at XHTML MP pages, their source look like the
following:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
...
...

So you see these pages have a different document type and some
other differences. So will the following code work and generate a valid
WAP 2.0 page?:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sometitle</title>
</head>
<body>
<h1>Hello</h1>
<p> style="color: rgb(0, 0, 187);"><?php 
style="color: rgb(0, 119, 0);">echo  style="color: rgb(0, 0, 187);">date style="color: rgb(0, 119, 0);">( style="color: rgb(221, 0, 0);">'h:i A, j-M-y' style="color: rgb(0, 119, 0);">);  style="color: rgb(0, 0, 187);">?></p>
</body>
</html>

The answer is “NO”? Why? Because XHTML MP pages needs to be
served with a different Content-Type than what is generated by .PHP
files. Normally when you runa s PHP script and it outputs something,
the content is served with Content-Type: text/html


What is
Content-Type?


It is a header (information about a particular resource)
returned to browser when it requests something from a server. When you
request an image, the server return the image with the header
image/png, image/jpeg etc. letting the browser know how the returned
content is to be interpreted.


PHP scripts can return contents of any type (using
the header() function), from text to
images and PDFs to ZIPs. And therfore
if we want to generate  XHTML MP pages, it can even do that
without doubt.


So what we need to do is, just change the above code a bit
adding a new line at the top so that the whole code look like the
following:



style="color: rgb(0, 0, 187);"><?php header
style="color: rgb(0, 119, 0);">( style="color: rgb(221, 0, 0);">"Content-type: application/vnd.wap.xhtml+xml; charset=UTF-8" style="color: rgb(0, 119, 0);">); style="color: rgb(0, 0, 187);">?>
style="color: rgb(0, 0, 0);"><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sometitle</title>
</head>
<body>
<h1>Hello</h1>
<p> style="color: rgb(0, 0, 187);"><?php  style="color: rgb(0, 119, 0);">echo  style="color: rgb(0, 0, 187);">date style="color: rgb(0, 119, 0);">( style="color: rgb(221, 0, 0);">'h:i A, j-M-y' style="color: rgb(0, 119, 0);">);  style="color: rgb(0, 0, 187);">?></p>
</body>
</html>

This will tell the browser that the content we are going to
serve is of the type XHTML MP. We always use the charset UTF-8 for
these pages, which is also told to the requesting browser.


Now the big question is, why we didn't do this for normal HTML
pages. Why didn't we have to tell the browser that content is of the
type “text/html” when it was so? Because PHP does it for us! Yes
whenever we output anything from PHP scripts, the PHP interpreter
outputs the default header (text/html) automatically. Just as the
PHP  interpreter finds anything in the script that needs to be
output, it first generates a header, the outputted content follows. For
example in the first script, the very first line (very first character
“<”) needs to be output to the browser. So before that, the PHP
interpreter sends a content type header (default – text/html).


Therefore, when we had to output our content with a different
header we had to make sure that it is done before PHP does it
automatically. Two headers  cannot be valid.


This is it for this post, do check back soon for more new
posts. Till then, good bye!

Custom Tags Parsing Using Regular Expressions

In the last post, we had created a simple
custom tag parsing script
using PHP string functions. In this post,
we are going to continue our discussion on custom tag parsing but rather using
Regular Expressions. Here we will see how regular expressions can used to parse
strings, we will also see where to and where not to use Regular Expressions.
Before continuing, I expect that you have a working knowledge of Regular Expressions
if not please first check out this
websites
.


Let us first create the previous custom tag parsing script using expressions:



<form name="form1" method="get" action="">

  <p>

    <!-- textarea should display previously wriiten text -->


    <textarea name="content" cols="35" rows="12" id="content"><? if (isset($_GET['content'])) echo $_GET['content']; ?></textarea>


  </p>

  <p>

    <input name="parse" type="submit" id="parse" value="Parse">

  </p>

</form>

<?



if(isset($_GET['parse']))


{

    
$content $_GET['content'];

    
//convert newlines in the text to HTML "<br />"


    //required to keep formatting (newlines)

    
$content nl2br($content);

    

    
//PHP function 'eregi_replace' replaces all occurences of the expression with the one mentioned


    //'\\1' is the string matched (one in parentheses '()' in the regular expression

    //it's a 'eregi_replace' thing not PHP's




    
$content eregi_replace('\.b\.(.+)\./b\.''<strong>\\1</strong>'$content);

    
$content eregi_replace('\.i\.(.+)\./i\.''<i>\\1</i>'$content);


    

    
//now the variable $content contains HTML formatted text

    //display it

    
echo '<hr />';


    echo 
$content;

}

?>



But should we use regular expressions here, answer is NO, because, first regular
expressions run slower and they add a fair bit of complexity where the same
thing could have been done easily using just string functions.


The reason for me staring this post with something contradicting to the theme
of the post is because people tend to avoid regular expressions thinking that
the same thing can be done otherwise (I just gave them one more chance!). Well
it may be case sometimes but in many other cases where complex string manipulation
is required with efficiency there is but one choice, regular expressions. The
next example will illustrate this.


For this example we will parse ‘*’ (asterisk) and ‘_’
(underscore) for bolding and italicizing text (as in Google Talk / IM applications).
The following text:


Hello *World*. Hello _World_.


Will be parsed and displayed as:


Hello World. Hello World.


It is quite obvious that both tags’ start and end tags are the same.
Now let us see how this can be implemented (using regular expressions).



<form name="form1" method="get" action="">

  <p>

    <!-- textarea should display previously wriiten text -->


    <textarea name="content" cols="35" rows="12" id="content"><? if (isset($_GET['content'])) echo $_GET['content']; ?></textarea>


  </p>

  <p>

    <input name="parse" type="submit" id="parse" value="Parse">

  </p>

</form>

<?



if(isset($_GET['parse']))


{

    
$content $_GET['content'];

    
//convert newlines in the text to HTML "<br />"


    //required to keep formatting (newlines)

    
$content nl2br($content);

    

    
//match anything between the tags but not the tag itself


    //otherwise '*hello* world *hello*'

    //will be print 'hello* world *hello' in bold

    //and not 'hello(in bold) world hello(again in bold)'




    
$content eregi_replace('\*(.[^*]+)\*''<strong>\\1</strong>'$content);

    
$content eregi_replace('\_(.[^_]+)\_''<i>\\1</i>'$content);


    

    
//now the variable $content contains HTML formatted text

    //display it

    
echo '<hr />';


    echo 
$content;

}

?>


If we try to implement this using string functions it will take quite a lot
more lines of extra coding but I leave that to you.


Previous Posts:


Basic "Custom Tags" Parsing Script

Basic “Custom Tags” Parsing Script

Today we are going to create a basic Custom Tags parsing script that will parse
special symbols (tags) in text for formatting purpose. Just like writing <b>BOLD</b>,
a web browser parses it as “BOLD” in bold letters, same way our
script will parse tags created by us. One very popular example of custom tag
parsing for formatting purpose is, BBCode which most of the bulletin boards
use to let users format their posts.


This will be a basic example of parsing custom tags so we will only be parsing
two tags. One will convert the enclosing text into bold and other will be used
for italics. After understanding the basic idea, you can easily add more tags
according to your needs and can also use it wherever necessary. One of its good
use will be in Shout Boxes that we had designed a few months back.


Though many would like the use of Regular
Expressions
for parsing, we will not be using them here. For the sake
of simplicity, we will be using only the basic string manipulation functions
available in PHP.


If you look at the code below, you can see an array (2D) holding our custom
tags. Here we’ll be having four information for each tag. Start tag, end
tag (both defined by us), HTML start tag and HTML end tag. To make this more
clear, let’s suppose we want to parse the text “[b]Text[/b]
so that it’s displayed as “Text” in bold. Our start (custom)
tag will be [b], end tag will be [/b], HTML start
tag will be <b> and HTML end tag will be </b>.


As we will be parsing two different custom tags, we have eight elements in
the array. If you want to add more tags, add four elements for each tag, just
like the way the others are. No need to change anything else.


The code:



<form name="form1" method="get" action="">

  <p>

    <!-- textarea should display previously wriiten text -->


    <textarea name="content" cols="35" rows="12" id="content"><? 
if (isset(
$_GET['content'])) echo $_GET['content']; ?></textarea>


  </p>

  <p>

    <input name="parse" type="submit" id="parse" value="Parse">

  </p>

</form>

<?



if(isset($_GET['parse']))


{

    
$content $_GET['content'];

    
//convert newlines in the text to HTML "<br />"


    //required to keep formatting (newlines)

    
$content nl2br($content);

    

    
/* CUSTOM TAGS

    -----------

    */




    //For Tag 1

    
$tag[0][0] = '[b]';

    
$tag[0][1] = '[/b]';


    
$tag[0][2] = '<strong>';

    
$tag[0][3] = '</strong>';




    
//For Tag 2    

    
$tag[1][0] = '[i]';

    
$tag[1][1] = '[/i]';


    
$tag[1][2] = '<i>';

    
$tag[1][3] = '</i>';




    
//count total no. of tags to parse

    
$total_tags count($tag); //2 for now


    

    //parse our custom tags adding HTML tags instead

    //which a browser can understand

    
for($i 0$i<$total_tags$i++)


    {    

        
$content str_replace($tag[$i][0],$tag[$i][2],$content);


        
$content str_replace($tag[$i][1],$tag[$i][3],$content);


    }

    

    
//now the variable $content contains HTML formatted text

    //display it

    
echo '<hr />';


    echo 
$content;

}

?>


The code is pretty straightforward. Isn’t it!


Previous Posts:


Unable to load dynamic library php_curl.dll: Error message in PHP

PHP logoIn Windows, while trying to use "curl" extension with PHP 5.2/Apache 2; you may encounter a blank page. If you open up the error log file in Apache (%APACHE_HOME%\logs\error.log); you may see an error message as follows.

"PHP Warning: PHP Startup: Unable to load dynamic library '%PHP_HOME\\ext\\php_curl.dll' - The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log for more detail."

This error message can be caused due to some version conflicts on a set of DLLs that are already available inside %windows%\system32 directory.

First check the %windows%\system32 directory to see whether the following DLL files are already available.
curl logo
  1. libeay32.dll
  2. ssleay32.dll
If those are available, then you would be able to resolve the issue as follows. (However if they are not available, you would need to find some alternative solution).

Now you must first rename the above two DLL files. We did as follows by adding an .old extesion.
  1. libeay32.dll.old
  2. ssleay32.dll.old
Both these libeay32.dll and ssleay32.dll files are available inside your %PHP_HOME% directory. Now copy both of those DLL files into %windows%\system32 folder.

Now try to use the "curl" extension, and it will start to function properly. (Sometimes you may need to restart Windows).

However if this tip could not resolve your issue, make sure to restore the previous DLLs.

Simple File Uploading Script in PHP

Simple File Uploading Script in PHP


PHP is undoubtedly the best programming language when it comes to web programming.
It gives us so many features and capabilities, a few of which we’ve discussed
already. So continuing with that, today we’ll see how we can use a few
lines of code to create a script that’d allow file uploading right from
the web browser. File upload feature is definitely useful kinds of website but
at the same time very much vulnerable to malicious attacks as well. So use it
with a LOT of precautions!


For this example, we’ll need a front-end web page that’ll accept
the file from the user and a backend script to process and store the file. Let’s
look at the codes of each:


upload.html:



<html>
<body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>


Here we have a HTML form that calls the script on submission. The method of
data sending should be “POST” and there should be and
enctype as “multipart/form-data” which means we can
upload binary form data. The input type “file” opens the File Input
Box that’d let the user browse for the file. The submit button “Upload”
submits the form as usual.


upload_file.php:


<?php 
if ($_FILES["file"]["error"] > 0)
    echo 
"Error:: " $_FILES["file"]["error"] . "<br />";
else
{
    if (
file_exists($_FILES["file"]["name"]))
    {
        echo 
$_FILES["file"]["name"] . " already exists. ";
    }
    else
    {
        
move_uploaded_file($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]);
        echo 
"File <b>" $_FILES["file"]["name"] . "</b> uploaded successfully!";
    }
}
?>

Just like we had POST form data in $_POST[] and GET data in $_GET[]
array same way to have files sent to script we use $_FILES[] array.




  • $_FILES["file"]["error"]: Tells
    us if there is any error in uploading. Note that “file” the
    first string index of the array is the name of the “File” input
    type from the HTML form.




  • $_FILES["file"]["tmp_name"]:
    All the files sent to any script is stores in a temporary directory by PHP,
    this tells us the location of that temporary file.




  • $_FILES["file"]["name"]:
    It tells us the name of the file on the users’ computer.




  • move_uploaded_file(): As files sent to scripts
    are just stored temporarily, we have to save it to some place, for this
    we use this PHP function. It’s first parameter is the temporary file
    location and second is the place we need to store the file and with what
    name. We are storing it to the same directory the script is in and with
    name same as on the users’ computer.




NOTE: This is just meant for example purpose and you shouldn’t have this
on your server as it is an open invitation to hackers/spammers. If you need
upload facility on your website in all the cases you should have some kind of
authentication
system
that'd only allow registered users to upload anything. you should
also accept only certain file types. you wouldn't like someone uploading/running
spamming script off your server. Would you? there may be a few other precautions
that you may need to take depending on the purpose you intend to use the script
for.


Previous Posts:


Check out this stream