Picture Php

<?php // Connect to database $errmsg = ""; if (! @mysql_connect("localhost","trainee","abc123")) { $errmsg = "Cannot connect to database"; } @mysql_select_db("test"); // First run ONLY - need to create table by uncommenting this // Or with silent @ we can let it fail every subsequent time ;-) $q = < < <CREATE create table pix ( pid int primary key not null auto_increment, title text, imgdata longblob) CREATE; @mysql_query($q); // Insert any new image into database if ($_REQUEST[completed] == 1) { // Need to add - check for large upload. Otherwise the code // will just duplicate old file ;-) // ALSO - note that latest.img must be public write and in a // live appliaction should be in another (safe!) directory. move_uploaded_file($_FILES['imagefile'] ['tmp_name'],"latest.img"); $instr = fopen("latest.img","rb"); $image = addslashes(fread($instr,filesize("latest.img"))); if (strlen($image) < 149000) {


how to add picture using php

Transcript of Picture Php

Page 1: Picture Php


// Connect to database

$errmsg = "";if (! @mysql_connect("localhost","trainee","abc123")) {        $errmsg = "Cannot connect to database";        }@mysql_select_db("test");

// First run ONLY - need to create table by uncommenting this// Or with silent @ we can let it fail every subsequent time ;-)

$q = < < <CREATEcreate table pix (    pid int primary key not null auto_increment,    title text,    imgdata longblob)CREATE;@mysql_query($q);

// Insert any new image into database

if ($_REQUEST[completed] == 1) {        // Need to add - check for large upload. Otherwise the code        // will just duplicate old file ;-)        // ALSO - note that latest.img must be public write and in a        // live appliaction should be in another (safe!) directory.        move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img");        $instr = fopen("latest.img","rb");        $image = addslashes(fread($instr,filesize("latest.img")));        if (strlen($image) < 149000) {                mysql_query ("insert into pix (title, imgdata) values (\"".                $_REQUEST[whatsit].                "\", \"".                $image.                "\")");        } else {                $errmsg = "Too large!";        }}

// Find out about latest image

$gotten = @mysql_query("select * from pix order by pid desc limit 1");if ($row = @mysql_fetch_assoc($gotten)) {

Page 2: Picture Php

        $title = htmlspecialchars($row[title]);        $bytes = $row[imgdata];} else {        $errmsg = "There is no image in the database yet";        $title = "no database image available";        // Put up a picture of our training centre        $instr = fopen("../wellimg/ctco.jpg","rb");        $bytes = fread($instr,filesize("../wellimg/ctco.jpg"));}

// If this is the image request, send out the image

if ($_REQUEST[gim] == 1) {        header("Content-type: image/jpeg");        print $bytes;        exit ();        }?>

<html><head><title>Upload an image to a database</title><body bgcolor=white><h2>Here's the latest picture</h2><font color=red><?= $errmsg ?></font><center><img src=?gim=1 width=144><br><b><?= $title ?></center><hr><h2>Please upload a new picture and title</h2><form enctype=multipart/form-data method=post><input type=hidden name=MAX_FILE_SIZE value=150000><input type=hidden name=completed value=1>Please choose an image to upload: <input type=file name=imagefile><br>Please enter the title of that picture: <input name=whatsit><br>then: <input type=submit></form><br><hr>By Graham Ellis - [email protected]</body></html>

PHP MySQL example: image gallery (blob-storage)abstract This is a simple example of photo-gallery script, which uses MySQL table (BLOB field)

Page 3: Picture Php

to store images. Trivial password-protection, uploading and deleting images are supported. For Apache-version of PHP there is advanced browser-caching support (using If-Modified-Since header). compatible  PHP 4.3.0 or higher PHP 5

There are three notable parts of the script:

main page generation --

generates HTML code for the list of uploaded photos, forms for photo deletion and uploading

image uploading --

processes POST request: checks password, uploads photo to database or deletes it

image showing --

Fetches image information from MySQL database and sends image do browser. If PHP is installed as mod_php (for Apache), does If-Modified-Since HTTP header checking.

Image gallery example uses following table to store all of its data:

source code: MySQL / SQL CREATE TABLE `ae_gallery` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(64) character SET utf8 NOT NULL, `ext` varchar(8) character SET utf8 NOT NULL, `image_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `data` mediumblob NOT NULL, PRIMARY KEY (`id`) ); 

You can use any name for this table, just change $table variable at the begining of the image gallery code.

We use following functions in this example:


mysql_connect - connects to MySQL server mysql_select_db - select database

Page 4: Picture Php

mysql_query - send query mysql_fetch_row - get current row from result table mysql_real_escape_string - escaping string to use it in MySQL query mysql_num_fields - get number of rows

PHP get_magic_quotes_gpc - checking if PHP add slashes before quotes in input

parameters stripslashes - remove odd slashes trim - remove unnecessary spaces in the beginning and ending of string getimagesize - return image information as an array. Third element of array --

image type. file_get_contents - loads whole file into memory php_sapi_name - returns the name of PHP Server API apache_request_headers - gets some special header information from Apache strtotime - convert textual representation of time to integer (number of seconds

since 1970) header - sends HTTP header to browser

You can get help on this functions typing "php function-name" in any good search engine

Before using following example create sql-table (execute CREATE TABLE query above) and change variables ($db_host, $db_user, $db_pwd, $database, $table) to your MySQL / database settings.

source code: php<?php$db_host = 'localhost'; // don't forget to change $db_user = 'mysql-user'; $db_pwd = 'mysql-password';

$database = 'test';$table = 'ae_gallery';// use the same name as SQL table

$password = '123';// simple upload restriction,// to disallow uploading to everyone

if (!mysql_connect($db_host, $db_user, $db_pwd))    die("Can't connect to database");

if (!mysql_select_db($database))    die("Can't select database");

// This function makes usage of// $_GET, $_POST, etc... variables// completly safe in SQL queriesfunction sql_safe($s){

Page 5: Picture Php

    if (get_magic_quotes_gpc())        $s = stripslashes($s);

    return mysql_real_escape_string($s);}

// If user pressed submit in one of the formsif ($_SERVER['REQUEST_METHOD'] == 'POST'){    // cleaning title field    $title = trim(sql_safe($_POST['title']));

    if ($title == '') // if title is not set        $title = '(empty title)';// use (empty title) string

    if ($_POST['password'] != $password)  // cheking passwors        $msg = 'Error: wrong upload password';    else    {        if (isset($_FILES['photo']))        {            @list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']);            // Get image type.            // We use @ to omit errors

            if ($imtype == 3) // cheking image type                $ext="png";   // to use it later in HTTP headers            elseif ($imtype == 2)                $ext="jpeg";            elseif ($imtype == 1)                $ext="gif";            else                $msg = 'Error: unknown file format';

            if (!isset($msg)) // If there was no error            {                $data = file_get_contents($_FILES['photo']['tmp_name']);                $data = mysql_real_escape_string($data);                // Preparing data to be used in MySQL query

                mysql_query("INSERT INTO {$table}                                SET ext='$ext', title='$title',                                    data='$data'");

                $msg = 'Success: image uploaded';            }        }        elseif (isset($_GET['title']))      // isset(..title) needed            $msg = 'Error: file not loaded';// to make sure we've using                                            // upload form, not form                                            // for deletion

        if (isset($_POST['del'])) // If used selected some photo to delete

Page 6: Picture Php

        {                         // in 'uploaded images form';            $id = intval($_POST['del']);            mysql_query("DELETE FROM {$table} WHERE id=$id");            $msg = 'Photo deleted';        }    }}elseif (isset($_GET['show'])){    $id = intval($_GET['show']);

    $result = mysql_query("SELECT ext, UNIX_TIMESTAMP(image_time), data                             FROM {$table}                            WHERE id=$id LIMIT 1");

    if (mysql_num_rows($result) == 0)        die('no image');

    list($ext, $image_time, $data) = mysql_fetch_row($result);

    $send_304 = false;    if (php_sapi_name() == 'apache') {        // if our web server is apache        // we get check HTTP        // If-Modified-Since header        // and do not send image        // if there is a cached version

        $ar = apache_request_headers();        if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists            ($ar['If-Modified-Since'] != '') && // not empty            (strtotime($ar['If-Modified-Since']) >= $image_time)) // and grater than            $send_304 = true;                                     // image_time    }

    if ($send_304)    {        // Sending 304 response to browser        // "Browser, your cached version of image is OK        // we're not sending anything new to you"        header('Last-Modified: '.gmdate('D, d M Y H:i:s', $ts).' GMT', true, 304);

        exit(); // bye-bye    }

    // outputing Last-Modified header    header('Last-Modified: '.gmdate('D, d M Y H:i:s', $image_time).' GMT',            true, 200);

    // Set expiration time +1 year

Page 7: Picture Php

    // We do not have any photo re-uploading    // so, browser may cache this photo for quite a long time    header('Expires: '.gmdate('D, d M Y H:i:s',  $image_time + 86400*365).' GMT',            true, 200);

    // outputing HTTP headers    header('Content-Length: '.strlen($data));    header("Content-type: image/{$ext}");

    // outputing image    echo $data;    exit();}?><html><head><title>MySQL Blob Image Gallery Example</title></head><body><?phpif (isset($msg)) // this is special section for                 // outputing message{?><p style="font-weight: bold;"><?=$msg?><br><a href="<?=$PHP_SELF?>">reload page</a><!-- I've added reloading link, because     refreshing POST queries is not good idea --></p><?php}?><h1>Blob image gallery</h1><h2>Uploaded images:</h2><form action="<?=$PHP_SELF?>" method="post"><!-- This form is used for image deletion -->

<?php$result = mysql_query("SELECT id, image_time, title FROM {$table} ORDER BY id DESC");if (mysql_num_rows($result) == 0) // table is empty    echo '<ul><li>No images loaded</li></ul>';else{    echo '<ul>';    while(list($id, $image_time, $title) = mysql_fetch_row($result))    {        // outputing list        echo "<li><input type='radio' name='del' value='{$id}'>";        echo "<a href='{$PHP_SELF}?show={$id}'>{$title}</a> &ndash; ";        echo "<small>{$image_time}</small></li>";    }

    echo '</ul>';

Page 8: Picture Php

    echo '<label for="password">Password:</label><br>';    echo '<input type="password" name="password" id="password"><br><br>';

    echo '<input type="submit" value="Delete selected">';}?>

</form><h2>Upload new image:</h2><form action="<?=$PHP_SELF?>" method="POST" enctype="multipart/form-data"><label for="title">Title:</label><br><input type="text" name="title" id="title" size="64"><br><br>

<label for="photo">Photo:</label><br><input type="file" name="photo" id="photo"><br><br>

<label for="password">Password:</label><br><input type="password" name="password" id="password"><br><br>

<input type="submit" value="upload"></form></body></html>

Author: D.Shaun Morgan

Versions and Skill Level PHP Version - PHP 5x MYsql Version - 5 Reader skill level - Intermediate

Tutorial Outline: 1. Creating a Test Mysql Database 2. Example php Database Function 3. Explanation of Database Function 4. Php Script to Load Images in Mysql Database 5. Explanation of Image Script

See Also: 1. How to Get Images Out of MySql Database 2. PHP Manual "base64_decode()"3. PHP Manual "chunk_split()"4. PHP Manual "convert_uuencode()"5. PHP Manual "RFC 2045 section 6.8"

Bookmark This Tutorial

Page 9: Picture Php

In this tutorial I will show you how to store images in a mysql database. I strive to make this tutorial as simple as possible. The example scripts that I provide here are intended to show you how to simply get a single image into your database. It will be up to you to write other scripts using php loops -- and functions like:

is_dir() is_file()

Creating a Test Mysql Database

Since it is impossible for me know if you already have a mysql database set up, I will include a fictitious database and table for this tutorial. The database will be called test_imgs. It will contain a single table called pictures.

id pics ext gender

1 retergfghfghterhgcfnt

hy6e5ghjwtjthj jpg female

1. "id" is primary, key, not null, and auto_increment2. "pics" blob not null3. "ext" is varchar(4) not null4. "gender" is varchar(7) not null5. I will assume English mysql defaults for everything else.6. I am calling the directory "/test/."7. Practice script "test.php"

Example Php Database Function

Before I can put anything in my database, I will need to connect to it. I have decided to write a function for this task.

function database_connect($db_host, $db_user, $db_pw, $db_name, &$db_selected, &$connection){

$connection = mysql_connect($db_host, $db_user, $db_pw);

if (!$connection){

die("Could not Connect to $db_host");


Page 10: Picture Php

$db_selected = mysql_select_db($db_name, $connection);

if (!$db_selected){

die( "Could not select database $db_name");



Explanation of Database Function

I named my function "database connect" for obvious reasons, then passed the following arguments:

1. $db_host -- Database Host2. $db_user -- Database User Name3. $db_pw -- Database Password4. $db_name -- Database Name5. &$db_selected -- Passed by reference6. &$connection -- Passed by reference

Arguments 1 through 4 need no explanation. Five and six were passed by reference so that, if I need to, I can used them outside the function without declaring them "global," or returning them. "$db_selected" will be of type "bool," which provides a great way to see if the database you are trying to connect to was selected. I suggest that you comment out the "die()" functions when you are not troubleshooting your code.

Just to make note of it; php does not require that the programmer declare a type for functions or variables. In a programming language like C, the coder would have to declare the above function "VOID" because it does not return anything.

Bookmark This Tutorial

Php Script to Load Images in Mysql Database

Now lets get down to the task of storing images in a mysql database.

Page 11: Picture Php

$handle = fopen("testpic.jpg", "rb");$img = fread($handle, filesize('testpic.jpg'));fclose($handle);//die($img);

$img = base64_encode($img);

database_connect('localhost', 'root', 'admin', 'img_test', &$db_selected, &$connection);

$sql = "insert into pictures values(null,'$img','jpg','female')";

mysql_query($sql) or die('Bad Query at 12');

echo "Success! You have inserted your picture!";?>

Explanation of Image Script

Notice that I used "fopen(), fread(), and fclose()" to get the contents of "testpic.php" and store it in a variable -- $img.

Next, I take $img and run it through "base64_encode()."( If you need an explanation of base64_encode and images, I suggest you Google it. Just know that it works when storing images -- 'That's enough for right now, I think.)

Lastly, after a little SQL magic, I stick the encoded data from my test picture into the database. Viola! Now I have a jpeg image stored in mysql. Make note that I made a point to record the file extension along with the picture itself. I will be using that information when I am ready to get images out of my sql database.

How to get images out of mysql database with php and use them on my webpagesAuthor: D.Shaun Morgan

Versions and Skill Level PHP Version - PHP 5x Mysql Version - 5 Reader skill level - Intermediate

Tutorial Outline: 1. Creating a Test Mysql Database 2. Php Script to Load Images in Mysql Database

Page 12: Picture Php

3. Php Script to retrieve images from mysql database 4. Example of calling php script with img HTML tag 5. Explanation of Image Script

See Also: 1. How to store images in MySql database

Bookmark This Tutorial

This tutorial expands on another database/image how-to How to Store Images in Mysql Database. In the "Images In" tutorial I showed you the basic steps needed to open a file (your image file) and read it into a variable ($img), convert that file using php's base64_encode() function, and stick that file into a Mysql database. Now, you will learn how to bring those images back out of your Mysql database, and output them to a web browser.

Retrieving Images From Mysql Database With phpTo begin, do the following:

1. Create a mysql database with a table matching (Database Example)2. Create a directory on your server to place files in (test)3. Create a file named "test01.php" and place example 1 in it (below)4. Create a file named "test02.php" and place example 2 php script in it (below)5. Create a file named "test03.php" and place example 3 HTML in it (below)6. Copy the following test images and save them in your test folder

Be certain that you have changed the database username, password et cetera so the test scripts can access your database server.

>>NOTE>> If you were looking for a tutorial on how to use php to store and retrieve bmp images, please read on... YOU WILL BE LOOKING FOR A LONG TIME! Bmp images are so large that they find little use in web development. Thus, there is very little support for it in php. You will do well to just gear your website toward jpg, gif or png. IF

Page 13: Picture Php

you are insisting on using bmp, you will do better to store them in a folder on your web server with unique names, and record their locations in your database. Storing the location of your pics in mysql database is covered here at mrarrowhead.com. Use the search function to find it.

Database example

id pics ext gender

1 retergfghfghterhgcfnt

hy6e5ghjwtjthj jpg female

1. Database name is "test_imgs"2. Table name is pictures3. "id" is primary, key, not null, and auto_increment4. "pics" blob not null5. "ext" is varchar(4) not null6. "gender" is varchar(7) not null7. I will assume English mysql defaults for everything else.8. Practice script "test.php"

Example 1<?php$host = '';

$user = '';

//$pw = '';

//$db = '';

$testpic = 'testpic.jpg';$ext = 'jpg';

//$testpic = 'testpic.gif';//$ext = 'gif';

//$testpic = 'testpic.png';//$ext = 'png';



$handle = fopen($testpic, "rb");$img = fread($handle, filesize($testpic));fclose($handle);

Page 14: Picture Php

$img = base64_encode($img);

$sql = "insert into pictures values(null,'$img','$ext','female');";

mysql_query($sql) or die('Bad Query at 12'.mysql_error());

echo "Success! You have inserted your picture!";?>

< href="test02.php">Next</a>

Example 2<?php$host = '';$user = '';$pw = '';$db = '';



$sql = "select pic, ext from pictures where id='1'";

$result = mysql_query($sql) or die('Bad query at 12!'.mysql_error());

while($row = mysql_fetch_array($result,MYSQL_ASSOC)){

$db_img = $row['pic'];$type = $row['ext'];


$db_img = base64_decode($db_img); //print_r($db_img );

$db_img = imagecreatefromstring($db_img);if ($db_img !== false) { switch ($type) {case "jpg":header("Content-Type: image/jpeg");imagejpeg($db_img);

Page 15: Picture Php

break;case "gif":header("Content-Type: image/gif");imagegif($db_img);break;case "png":header("Content-Type: image/png");imagepng($db_img);break;}


Example 3<img src="test02.php"/>

Tutorial Conclusion and Explanation

After building the database, and uploading all the example files and images to your server, simply navigate to the test01.php script on your server. By default the test script should open testpic.jpg and send it to your mysql server with an id of "1". Click the next link and go to test_02.php to view your image. Then type test03.php into your browser's nav bar.

Notice that on the test03.php page, I inserted test_02.php in the img tag.

<img src="test02.php" alt=""/>

This works great for creating on the fly images with your html. Using the img tag allows me to call a php script without using an include, or iframe. It also sets up the right header for my image to display. If you notice on test02.php, I had to send an header before I used the image function to output my image to browser. The php header function is not necessary if you use the test03.php method. Comment the header functions out of test02.php, then run both test02.php and test03.php. test03.php will give an image, and the former will give a mess.

Repeat the steps above for the .gif and .png images. I suggest you practice with some loops, if statements, and a form so that your php script can handle all three image situations based on a user's choice.


Page 16: Picture Php

php also supports wbmp for wireless. You can find the appropriate functions in the php manual.


This article is an introduction to using the blob column type in MySQL. The concept is introduced by familiarising users with uploading and storing images in a MySQL table.

Definitely a controversial topic in PHP-land, but at least knowing how to do it will help you make a decision on whether or not it’s for you.

The article covers the following:

Isn’t this a bad idea? What is a BLOB? Creating an image table The upload form Uploading the image The upload() function Display an image from the database Displaying all the information

This article was originally published at http://phpro.org, and is reproduced on PhpRiot with permission of the author, Kevin Waterson.

Isn't This A Bad Idea?

This argument continues to rage and many lives have been lost trying to prove that this is a Bad Idea™. The facts are, this method of binary storage is very successful and has many advantages over filesystem storage. Some advantages are:

Referential integrity Ease of backup Saving of Inodes Easy categorisation Central point of operations

Many of the “nay sayers” will have you believe that storing of images or other binary data creates too much overhead. A large database can be stored on a RAW partition and in fact be faster as it has no filesystem overhead to contend with.

Page 17: Picture Php

Some would say that access is slow when SELECTing from the database, but most of these issues are caused by coders doing things like:

Listing 1 listing-1.sql select * from image_table

When all they needed was the image ID. You can see a benchmark of the perfomance of this where we used three methods of access for an image:

Access image from file Store image in filesystem and store the url in the database Store the image in the database

The results may surprise you.

What Is A Blob?

Binary Large Object. In short, a blob is a field type for storing Binary Data. MySQL has four BLOB types:





For more information on this we highly recommend you read the MySQL manual section on BLOBs.

Next: Creating An Image Table

Creating An Image Table

Of course we need to create a table to store our images in. Here is a simple table:

Listing 2 listing-2.sql create table testblob ( image_id tinyint(3) not null default '0', image_type varchar(25) not null default '', image blob not null, image_size varchar(25) not null default '', image_ctgy varchar(25) not null default '', image_name varchar(50) not null default '');

Ok, nothing dramatic here, but let’s break it down.

Page 18: Picture Php

First we have an id field, this should be an auto incremented field so we avoid confusion when selecting.

Next we have the image type (mime type). This is handy as we can use PHP to determine this and use it for sending the correct headers when we need to display the image.

Next we have the image_blob field. This is the field that will contain the actual image data.

Then we have the image size as determined by getimagesize().

Then we have a category for our images, you may wish to have have a second table of categories to populate your form dropdown for this. But for our purposes we will only be using three.

Finally, we have the image name. You can add more items to this table such as exif info and descriptions, but for our purposes we will keep it simple.

The Upload Form

The upload for is basically the same as for any file upload

Listing 3 listing-3.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head><title>File Upload To Database</title></head> <body> <h3>Please Choose a File and click Submit</h3> <form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <input type="hidden" name="MAX_FILE_SIZE" value="10000000" /> <input name="userfile[]" type="file" /> <input type="submit" value="Submit" /> </form> </body></html>

It is important to use the enctype="multipart/form-data" so that the browser uploads the binary data correctly.

No surprises here, although we do stress you have the hidden field for MAX_FILE_SIZE. This can be handy for not allowing images that are too large to be uploaded. Remember also about the PHP upload_max_filesize setting.

Page 19: Picture Php

Uploading The Image

Here we get funky and can stick the image into the database.

As with all user input it is vital that it is checked with some sort of sanity checking to be sure we are getting what we asked for.

In this case, we are asking for image files of types that are supported by getimagesize().

First of all, we need to check that when somebody accesses our page the they have POSTed a file. If they have not, we can echo a simple message and if they have, we can call the upload() function that we will create. Please note that this function uses PHP5 exceptions.

Listing 4 listing-4.php <?php // check if a file was submitted if(!isset($_FILES['userfile'])) { echo '<p>Please select a file</p>'; } else { try { upload(); // give praise and thanks to the php gods echo '<p>Thank you for submitting</p>'; } catch(Exception $e) { echo $e->getMessage(); echo 'Sorry, could not upload file'; } }?>

The Upload Function

Here we need to do several things to successfully upload the image. We need to create a function that does several things. An outline might look like this:

1. Check the file is of an allowed type2. Check if the uploaded file is no bigger thant the maximum allowed size3. Format the binary data for insertion4. Connect to the database5. Insert the data

We have already checked that an image has been uploaded with the first if statement. We should also check that it is an uploaded file, so now we need to check if the file is of an allowed type with getimagesize(). We will begin our function with that and build on it from there.

Page 20: Picture Php

Listing 5 listing-5.php <?php // the upload function function upload(){ if(is_uploaded_file($_FILES['userfile']['tmp_name'])) { // check the file is less than the maximum file size if($_FILES['userfile']['size'] < $maxsize) { // prepare the image for insertion $imgData =addslashes (file_get_contents($_FILES['userfile']['tmp_name'])); // $imgData = addslashes($_FILES['userfile']); // get the image info.. $size = getimagesize($_FILES['userfile']['tmp_name']); // put the image in the db... // database connection mysql_connect("localhost", "$username", "$password") OR DIE (mysql_error()); // select the db mysql_select_db ("$dbname") OR DIE ("Unable to select db".mysql_error()); // our sql query $sql = "INSERT INTO testblob ( image_id , image_type ,image, image_size, image_name) VALUES ('', '{$size['mime']}', '{$imgData}', '{$size[3]}', '{$_FILES['userfile']['name']}')"; // insert the image if(!mysql_query($sql)) { echo 'Unable to upload file'; } } } else { // if the file is not less than the maximum allowed, print an error echo '<div>File exceeds the Maximum File limit</div> <div>Maximum File limit is '.$maxsize.'</div> <div>File '.$_FILES['userfile']['name'].' is '.$_FILES['userfile']['size'].' bytes</div> <hr />'; } }?>

Page 21: Picture Php

Displaying The Image

Now we have the ability to get the images into the database, we need to be able to get it out.

Here we see a simple script to display an image based on its image_id in the database. Of course you should do more checking on the value of $_GET['image_id'] here. We will call this file view.php.

Listing 6 file.php <?php // just so we know it is broken error_reporting(E_ALL); // some basic sanity checks if(isset($_GET['image_id']) && is_numeric($_GET['image_id'])) { //connect to the db $link = mysql_connect("localhost", "username", "password") or die("Could not connect: " . mysql_error()); // select our database mysql_select_db("testblob") or die(mysql_error()); // get the image from the db $sql = "SELECT image FROM testblob WHERE image_id=0"; // the result of the query $result = mysql_query("$sql") or die("Invalid query: " . mysql_error()); // set the header for the image header("Content-type: image/jpeg"); echo mysql_result($result, 0); // close the db link mysql_close($link); } else { echo 'Please use a real id number'; }?>

Displaying All The Information

Now we have the basic building blocks, we could create a script to see all the information about the image that we have stored in our table.

The trick here is to avoid sending headers twice. To do this we use two files. The first we will call file.php and we use the above view.php in our HTML img tag. Of particular

Page 22: Picture Php

importance here is not to make the mistake mentioned at the beginning of this tutorial of doing something silly like SELECT * FROM testblob.

This is not required and would slow us down in our query because we would need to store the image itself in memory when we are not going to use it yet. So we simply SELECT the other information from the fields that we do want.

Listing 7 view.php <?php // again we check the $_GET variable if(isset($_GET['image_id']) && is_numeric($_GET['image_id'])) { $sql = "SELECT image_type, image_size, image_name FROM testblob WHERE image_id=".$_GET['image_id']; $link = mysql_connect("localhost", "username", "password") or die("Could not connect: " . mysql_error()); // select our database mysql_select_db("testblob") or die(mysql_error()); $result = mysql_query($sql) or die("Invalid query: " . mysql_error()); while($row=mysql_fetch_array($result)) { echo 'This is '.$row['image_name'].' from the database<br />'; echo '<img '.$row['image_size'].' src="view.php?image_id='.$_GET['image_id'].'">'; } } else { echo 'File not selected'; }?>

From the above script we can see the first image from the database. At the top of the page it has echoed a little message and the image name from the database.

You could, as mentioned earlier store other information about the image in the same way and display it. In this script we also use the image_size field from that we had gained from getimagesize(). This stores the image width and height in a string that we can use in img tags.