Monday, April 23, 2007

Using PHP for more than HTML

It is mostly thought that PHP can be used only for making dynamic web pages. No. PHP can also be used to make dynamic images (jpg,gif,bmp,png..), javascript codes (js), Style sheets (css), XML files and in the advanced cases pdf's, docs etc.

So How do we know the php is a different file ?
By default the php file is rendered as a HTML file. The server does not need any recognition for the format of the php file, i.e, server doesn't care what the format is. But the browser does. So we have to notify the browser the content-type of the content we are sending to the browser.

This is done by

header("Content-Type: image/jpeg");

The header function adds or replaces the default headers. Thus here the default content type being html/plain-text is replaced by image/jpeg. Thus on the viewers browser the php file would be rendered as an image. Thus
<img src="">

would show an image if the coding is correct and the image format is correctly rendered.

More about returning images
header("Content-Type: image/jpeg");
echo file_get_contents("../images/some.jpg");

The above code returns a jpeg. But this is static everytime we see the some.jpg. The advantage of using php to return image is that you can provide a authentication validation, i.e, the user must have signed in to view the image. Thus automatically hot linking is prevented. (Hot linking is the use of images of other servers, by another server. for eg an image on displyed on
But precious server resources are also consumed.

Another advantage is by returning a random image :
header("Content-Type: image/jpeg");
$files = array("photo0.jpg","photo1.jpg","photo2.jpg");
$index = rand(0,2);
echo file_get_contents($file[$index]);

Returning an image from scratch
Suppose we want to display an image, say for example a bar graph or a random code or text segment from php. Using 100's of images is inefficient and time consuming. In these cases comes in the use of the GD library.

Returning other formats
Other formats can be returned from php via the same way by changing the Content-Type header and giving the appropriate body.
Example :

header("Content-Type: text/javascript");
function Foo()

echo "function Rand() { } ";

It is also a good practice to set the content-length header, in case you know the size of the body you are about to send in advance. (In case you are sending an image).

Common Content Types

HTML TEXTtext/html
Plain TEXTtext/plain
Cascading Style Sheetstext/css


Unknown said...

Dear sir,

What is future about php. in job wise in offering in MNC. pls send your valuable comment send my mail id is

Anonymous said...

Submitted into queue @ tweako