Inserting and displaying images in MySQL using PHP

Well working with images is quite easy task in MySQL  using php code. Some years back managing images in relational database is quite complex task as at those times relational databases are able to store only textual data so file path to the images are stored in database and images are stored and retrieved externally. Also special  file functions are necessary for retrieving  images this way and this approach is system dependent (because of path names used). Nowadays, almost all major DBMS support storing of images directly in database by storing images in the form of binary data. Here, I am explaining the method of storing and retrieving images in MySQL database using PHP code.

Inserting images in mysql-:

MySQL has a blob data type which can used to store binary data. A blob is a collection of binary data stored as a single entity in a database management system. Blobs are typically images, audio or other multimedia blob objects. MySQL has four BLOB types:

  • BLOB

All these types differ only in their sizes.

For my demonstration, lets us create a test table named test_image in MySQL having 3 columns show below-:

  • Id (INT) -Act as primary key for table.
  • Name (VARCHAR) – Used to store image name.
  • Image (BLOB) – Used to store actual image data.

You can use phpMyAdmin tool to create the above table else use the following MySQL query-:

create table test_image (
id              int(10)  not null AUTO_INCREMENT PRIMARY KEY,
name            varchar(25) not null default '',
image           blob        not null

PHP code to upload image and store in database-:

To upload the image file from client to server and then store image in MySQL database on server, I am posting here the PHP code for our test/sample table (test_image).

Please change the values of variables in file_constants.php file according to your system. Save the following scripts with names as shown in your web directory.




<head><title>File Insert</title></head>
<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" />


// check if a file was submitted
    echo '<p>Please select a file</p>';
    try {
    $msg= upload();  //this will upload your image
    echo $msg;  //Message showing success or failure.
    catch(Exception $e) {
    echo $e->getMessage();
    echo 'Sorry, could not upload file';

// the upload function

function upload() {
    include "file_constants.php";
    $maxsize = 10000000; //set to approx 10 MB

    //check associated error code
    if($_FILES['userfile']['error']==UPLOAD_ERR_OK) {

        //check whether file is uploaded with HTTP POST
        if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {    

            //checks size of uploaded image on server side
            if( $_FILES['userfile']['size'] < $maxsize) {  
               //checks whether uploaded file is of image type
              //if(strpos(mime_content_type($_FILES['userfile']['tmp_name']),"image")===0) {
                 $finfo = finfo_open(FILEINFO_MIME_TYPE);
                if(strpos(finfo_file($finfo, $_FILES['userfile']['tmp_name']),"image")===0) {    

                    // prepare the image for insertion
                    $imgData =addslashes (file_get_contents($_FILES['userfile']['tmp_name']));

                    // put the image in the db...
                    // database connection
                    mysql_connect($host, $user, $pass) OR DIE (mysql_error());

                    // select the db
                    mysql_select_db ($db) OR DIE ("Unable to select db".mysql_error());

                    // our sql query
                    $sql = "INSERT INTO test_image
                    (image, name)
                    ('{$imgData}', '{$_FILES['userfile']['name']}');";

                    // insert the image
                    mysql_query($sql) or die("Error in Query: " . mysql_error());
                    $msg='<p>Image successfully saved in database with id ='. mysql_insert_id().' </p>';
                    $msg="<p>Uploaded file is not an image.</p>";
             else {
                // if the file is not less than the maximum allowed, print an error
                $msg='<div>File exceeds the Maximum File limit</div>
                <div>Maximum File limit is '.$maxsize.' bytes</div>
                <div>File '.$_FILES['userfile']['name'].' is '.$_FILES['userfile']['size'].
                ' bytes</div><hr />';
            $msg="File not uploaded successfully.";

    else {
        $msg= file_upload_error_message($_FILES['userfile']['error']);
    return $msg;

// Function to return error message based on error code

function file_upload_error_message($error_code) {
    switch ($error_code) {
        case UPLOAD_ERR_INI_SIZE:
            return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
        case UPLOAD_ERR_FORM_SIZE:
            return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
        case UPLOAD_ERR_PARTIAL:
            return 'The uploaded file was only partially uploaded';
        case UPLOAD_ERR_NO_FILE:
            return 'No file was uploaded';
        case UPLOAD_ERR_NO_TMP_DIR:
            return 'Missing a temporary folder';
            return 'Failed to write file to disk';
            return 'File upload stopped by extension';
            return 'Unknown upload error';

Below is screenshot of above web page when executed by browser-:

With this you will be able to upload and store images in MySQL database. Also check for the presence of file in the database using phpMyAdmin or any other tool.

Displaying images stored in MySQL-:

Now we are in a position to write PHP code to see images stored by the above script. For that firstly save the script below with name file_display.php in your web directory.


 include "file_constants.php";
 // just so we know it is broken
 // some basic sanity checks
 if(isset($_GET['id']) && is_numeric($_GET['id'])) {
     //connect to the db
     $link = mysql_connect("$host", "$user", "$pass")
     or die("Could not connect: " . mysql_error());

     // select our database
     mysql_select_db("$db") or die(mysql_error());

     // get the image from the db
     $sql = "SELECT image FROM test_image WHERE id=" .$_GET['id'] . ";";

     // 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
 else {
     echo 'Please use a real id number';

Now you can see the images stored in the database using the following query string-:


You will see image which is stored  in database corresponding to id having value  “1” . You can use different numbers to see different images. Below is a sample screenshot-:

189 thoughts on “Inserting and displaying images in MySQL using PHP

  1. im a beginner in php…i have tried out the above script, but i was not able to view the image…how should i use the above query (http://{path_to_your_web_directory}/file_display.php/?id=1;) for retrieving the image

    • “http://{path_to_your_web_directory}/file_display.php/?id=1”
      This is not any query. This is address of the path where you copied file_display.php file. For example if you copied it in document root of web browser which is /var/www in most cases (if you installed web server using binaries), then the address on your local pc is
      Please tell me if still you are not getting the image displayed.

      • $finfo = finfo_open(FILEINFO_MIME_TYPE)

        u write this code in the file_insert.php . but dont specify related file related to this.

    • I think you had misunderstood the word “query string” in the post.
      Query string does not means any SQL query but it means any Url which sends data from client to server. In this case url is sending id from client to server.

  2. Hello Sir! i hav a problem while displaying the images back from mysqldb along with html code…i want to confine its height and width using the …every time i use any of html my screen goes blank…here’s a sample code of a script i’m using to display the picture..


    it works fine but when i add some html to it the screen just goes blank and doesn’t show any error too…i.e.

    It will be a great help of yours!
    Thanks in Advance!

    • You wrote “i want to confine its height and width using the …every time i use any of html my screen goes blank”.
      You can’t you HTML on the link/page which is generating image from database as resultant page is initialised using header(“Content-type: image/jpeg”) tag and it deletes all HTML elements on the current page before displaying file. Due to this reason you are seeing blank page.
      If you want to use HTML with image then correct way is to use HTML <img> tag with source to query string or anchor tag <a> with href as query string to make a target link of image.
      <td><a href=file_display.php?id=1>Target link</a></td<
      <td><img src=file_display.php?id=1 width=100 height=100></td>
      If still you are not able to do what you want then email me your source file as I am not able to find your code in your comment. My email id is

  3. Thanks Sir It Worked! I have also got another method, to save the image files on to the local hard disk and then accessing them as required…! Which one u think i go for i’m designing a Alumni website with some social networking features and a forum!

    • Ok. Yes I know about the second method. Actually the method to use for a particular web application depends upon the type and size of that application. If your application is large i.e you have to display a large number/size of images repeatedly then you should go for second method (storing only image path in database and actual images on filesystem). This will reduce the processing time to display images moreover consumes less resources. Secondly, if your application/no. of images/size of images is small then you can store them directly in database using method described in the post. This way it becomes easy to take backups and port application to another OS.

  4. first of all thanks for the code. I tried and it worked, now i want help from you.Cant i resize the image or user it inside the table as a background or apply any sort of operation with it. Currentlly the image is displayed in its full size.Now i want to resize.
    I would be grateful to you if you send me the technique to perform the action mentioned above.

    Ganesh Shrestha.

    • You can do any sort of operation with the generated image. You can save it, use it in table with specified width or height etc.
      Please refer to the previous comment (in reply to Dilip’s comment) in which I had explained the method to use image inside table cell. After that if you need any help feel free to ask me 🙂

    • Its shruti kittur from bvb college hubli, i need code to insert and display image from mysql database using php,please mail me that code as soon as possible.I am doing my M.C.A final year project,so i need that code so kindly help me by sending code for these two

  5. Hello Vikas, I quite appreciate your tutorial. My problem is that the image has to be submitted in a form containing other information like name, date of birth, etc. How can i submit image and other form data together to my database and then display the image and other form data using a search query. My database is expected to hold information of about 300 persons. Only image required is their passport. Thanks for ur help.

    • Hello Emeka, thanks for your appreciation.
      For submitting other data along with image, change the code given in file_insert.php (see above for code). You can add your custom form elements to represent other data inside the form created there. Then change the upload function to save the data from your form elements in the database. Basically, you have to change queries in the upload function. You can also add some error checking code if you want.
      For displaying data alongwith other fields read previous comments where you will find way to show resultant image inside table cell or way to create a link to your image.
      Try out and share your problem/experience.

  6. Hello Vikas, I have a question for you, if you could help me…
    I am just a beginner in mysql, and php(for now:).. I have stored my files for website in a BLOB field (mysql), some images from gallery, and I don’t know how to download them from database to hard disk.. Is there any phpMyAdmin option, or some other way to do it?
    Thank you in advance!

    • Hello Vladan, welcome to the world of opensource(specially php and mysql). I far as I understood your problem, you want to save image data in database into real images on filesystem. You can use “PHP GD and image functions” to do this task easily. Mostly you need function imagecreatefromstring() to create image resource from blob data and another function like imagejpeg() or imagepng() to save image resource in format you want. I am showing here code to save images in JPEG format. For that edit file_display.php file, comment lines which output image to browser and add following code after mysql query statement:-

      $image = imagecreatefromstring(mysql_result($result, 0));
      if ($image !== false) {
      echo “Image Successfully saved with name “.$_GET[‘id’].”.jpg”;
      else {
      echo “Can’t create image of this id.”;

      I think from above code you got a basic idea on how you can accomplish your task 🙂

    • And don’t forgot to use meaningful names while saving images which corresponds to the entry of that image in database. Also you can modify mysql query and use php loops to save all the database images to filesystem at once.

  7. sir,

    thanks for the code. It became very helpful to me. Now what i want is to display the image contained in the database. And also other features related to database and the images.

    thank you.

    • Hello Ganesh,
      Thanks for your appreciation. To just display image which is in database you need to customize the display.php file according to your database table structure. And you can display generated image in any format you want just like normal images. Read carefully previous comments, you can get lot of help from them.

    • In second method, you can just save the image name or image path (corresponding to the table row) in the database and actual images are placed in some folder. Even you can migrate from one method to another. For example- If you want to use second method for your blob images, you can convert and save them in some folder. Give meaningful name to the image being saved and then save that name or its relative path in the corresponding row of database (for referring back and using images). Then you can delete the blob images from the database. Again read previous comments for code to save image in JPEG extension and for comparisons of both methods.

  8. this article is more helpful , i am serch many days for how to insert image into mysql , now i get the idea for it , thank u very much

  9. your site is the best, alot of questions have been answered through your site. please help me with connecting my site to my database. i have tried so many ways and it couldn’t work.

    • Thanks for your appreciation. Detail you are giving is too less for anyone to understand the problem. Please explain in detail about what you are trying to do, what errors you are facing and about the softwares you are using like web server, database, os etc.

  10. On using the above code with the html syntax as i have to display image as well as other fields…I get

    Warning: Cannot modify header information – headers already sent by (output started at C:\wamp\caplacement\admin\employee\view_all_employee.php:9) in C:\wamp\caplacement\admin\employee\view_all_employee.php on line 13

    Please resolve this error and give an example in which name of the person,his photo n some other information is displayed

  11. thanku sir….
    code is really working …
    but it is working only for a single image..
    plz sir tell what are the changes should i made in the above code so that i can retrive “MORE THAN ONE IMAGES” from the data base…..

    • Code given here is for demonstration. Retrieving an image from database in nothing more than retrieving a single field value from database. So, to retrieve more images at once change the SQL query to fetch more images (Eg-: change condition to id < 10 ) then use PHP loop to repeatedly show images in different HTML table cells. Also, refer to previous comments. You will get a lot of help from them 🙂

  12. Thanku sir..
    i tried to retrive the images through a loop but this tym it is showing a very strange results.
    in place of images page is showing some strange characters like this..
    “7%%77777777777777777777777777777777777777777777777777ÿÀ^–”ÿÄÿÄ9!1Qa”Aq2‘¡#BR$3b±ÁÑS²ðñÿÄÿÄ”!A1Q2aqÿÚ ?©ûʏ읕3f¥é eµxRx-]z æLBµ¥$“䦝6Q¤6¤`:XmîO’IÃiùÔF£˜ÐðVAs­ÝÚÅ&=±¼:Z!ù”}isa®ñŒéѝZðqZ3ƒþ±NáæˆÑÄýjeÊH¤-¶ÙòýÊǶëL6U³³1—¼j6T· ÉYP×’5ô-¾ÎXá­ô–¦¡°w€Á è”

    m not getting any solution for this….
    so kindly plz help….
    my code is…

    // connect to mysql server
    $link = mysql_connect('localhost', 'root');
    if (!$link) {
    die('Not connected : ' . mysql_error());
    // connect to database server
    $db_selected = mysql_select_db('image', $link);

    if (!$db_selected) {
    die ('Database error : ' . mysql_error());

    $sql = "SELECT * FROM image";

    // the result of the query
    $result = mysql_query($sql) or die("Invalid query: " . mysql_error());
    while($row = mysql_fetch_assoc($result)){
    echo "ID: ".$row['sid'].", Name:".$row['title']
    .", image:".$row['img']."”;



    • Hi,
      You can’t display images like this. Database returns image data in binary form. This is the reason that you are getting strange characters. To display image you need to use header element of HTML. So, solution is that keep display.php file separate (without any loop) and create another file to select image id’s to be displayed then pass these id’s one by one to display.php file (inside the loop). Output data which display.php file returns for each image in separate table cell using img HTML tag.
      I think this much detail is enough. If still you are getting any problem feel free to ask !!!

  13. this is the table i have created in the database
    mysql> CREATE TABLE tbl_images (
    > id tinyint(3) unsigned NOT NULL auto_increment,
    > image blob NOT NULL,
    > PRIMARY KEY (id)
    > );
    and this the php code to retrieve it..

    BUT THE PROBLEM is that instead of displaying the image it just prints out the url once again!!!
    example : the output is ::: the same url

    • Hi,
      I think image data in not getting saved in database. In most of the cases, when you are seeing the url instead of image that means database is not returning image data. So, check your code to insert image in database and verify that images are successfully getting saved. Also, check the query you are using to get display data.

  14. this is my code for inserting into mysql.


    $tmpName = $_FILES[‘image’][‘tmp_name’];
    echo “$tmpName”;
    $fp = fopen($tmpName, ‘r’);
    $data = fread($fp, filesize($tmpName));
    $data = addslashes($data);
    $query = “INSERT INTO tbl_images”;
    $query .= “(image) VALUES (‘$data’)”;
    $results = mysql_query($query, $link) or die(“could not upload”. mysql_error());
    echo “done?!!!!!!!!”;
    echo “nothing”;

    i have sent u an attachment by mail..plz chk..

    • Hi,
      I study your ret.php file and got the error which you are doing. The
      problem was that you are sending output to browser prior setting the
      header of HTML page. Actually, you need to take care that your script
      is not sending any output before setting header of page. Even a single
      space outside php tags can cause this problem 😦
      I hope this solves your problem.

  15. I have not been able to successfully insert and then display images to and from mysql until trying your code. It works beautifully! Thank you! I should note that I had to change a setting in mysql settings, my.ini, changing max_allowed_packet = 1M to max_allowed_packet = 10M since the image files I was testing with were larger than 1M in size. Anyway, thanks again; I now have something I can build upon.

  16. Hi,

    I am trying to display an image from the image path stored in database. The problem is the image isn’t getting displayed. Pl. help me. Thanks.

    • If the images are stored in file system, then problem may be in path you are giving to retrieve the image or it may be permission issue.
      So, see the complete path you are using to fetch image using php echo statement and see if the image actually exists on this path.
      If your path is correct then verify whether web server have read permission on images or not. If not give necessary permissions.

      • Hi Vikas,

        Thanks for your inputs. I verified and is the problem with the path. I rectified my mistake and mentioned the path as “http://localhost/mypics/pic1.jpg” for the image pic1 lying under the mypics folder of the www directory in the WAMP. Thanks for your help. Your’s is a cool site!

  17. Hi here is my php code for insert the image in database.
    Now i want to store the imaze in small size in the folder when we load the image in uploaded file.
    plz tell me how i can store the small size in image folder.
    echo “Return Code: ” . $_FILES[“file”][“error”] . “”;
    echo “Upload: ” . $_FILES[“file”][“name”] . “”;
    echo “Type: ” . $_FILES[“file”][“type”] . “”;
    echo “Size: ” . ($_FILES[“file”][“size”] / 1024) . ” Kb”;
    echo “Temp file: ” . $_FILES[“file”][“tmp_name”] . “”;
    $new_path=$path. $_FILES[“file”][“name”];
    if (file_exists($new_path))
    echo $_FILES[“file”][“name”] . ” already exists. “;
    echo “Stored in: ” . $new_path;

    $sql =”INSERT INTO gallery (id, name, caption, status, images) VALUES (NULL, ‘$name’, ‘$caption’, ‘$status’, ‘$new_path’)”;



    Image Upload




    Upload Image

    • Hi,
      If you just want to store image in separate folder on server (when user uploads the image), you need not to insert image in database. Just rename the image from tmp_name to something useful and store it in your directory of choice using php filesystem functions.
      To process image (i.e. reduce size) use imagemagick convert command or some other utility of your choice.
      Finally, if you want to store images in database to some folder then read previous comments (in response to vladan). You will get a lot of help from them.

  18. Hai Vikas,

    I have a problem of UPDATE an image into database.. It will UPDATE the images when id=0, but will not UPDATE if its other than 0. In ‘function upload’ I just put ‘function upload($id)’ since need to UPDATE into database.
    If I put ‘function upload($id=4)’ it will only UPDATE image that has an ID = 4. The question is, How can I UPDATE image trough different ID??
    example code are like below..

    function upload($id)
    include “constants.php”;
    $maxsize = $_POST[‘MAX_FILE_SIZE’];

    if( $_FILES[‘userfile’][‘size’] < $maxsize)
    $imgData =addslashes (file_get_contents($_FILES['userfile']['tmp_name']));
    mysql_connect($host, $user, $pass) OR DIE (mysql_error());
    mysql_select_db ($db) OR DIE ("Unable to select db".mysql_error());

    $sql = 'UPDATE user SET ';
    $sql .= 'name = "'.($_FILES['userfile']['name']).'",';
    $sql .= 'image = "'.($imgData).'" ';
    $sql .= 'WHERE id = "'.$id.'";';
    mysql_query($sql) or die("Error in Query: " . mysql_error());

    'File exceeds the Maximum File limit
    Maximum File limit is ‘.$maxsize.’
    File ‘.$_FILES[‘userfile’][‘name’].’ is ‘.$_FILES[‘userfile’][‘size’].
    ‘ bytes

    • You are doing right. You need to pass id of corresponding image to update. Mechanism to pass id will depend upon your application. For example:- You can give a field to enter id in the image upload form or you can pass the id of image displayed to upload function (displayed in some form or other) to change it.
      About your code, I must say use php echo statement to see the correctness of SQL query and see if the id your are giving is correctively passed or not.

      • I have try an input id that will display the id of the image
        <input type="text" name="id" value="”/>

        But still cannot work and if I change the value it will remain the same. What do you mean by “pass the id of image displayed to upload function “?? is it “function upload($id)”? if it so I try to change to “function upload($id = 2)”, it will only change id=2. How do I change other than 2? without changing the function upload id to other numbers??

  19. Hi,
    Are you copying the id passed by the form into PHP $id variable?
    If not add this line before calling the upload($id) function (in file_insert.php file):-
    $id = $_POST[‘id’];
    I can’t help too much with this much of information. Try to remove error and if still you are not able to get your code work then send your code files to my email id ( so that I can debug them.

    • Inserting $id = $_POST[‘id’]; is the solution.. Thank you very much.. 🙂 as you motto says “Life and Computers are Simple, Lets don’t Complicate them” 😀

  20. hi, the upload is ok but when i try the download part this is what it returns:

    also using “header(“Content-type: image/jpeg”);” in the middle of the code causes problem. can you please help me?

    • Hi,
      Problem is with the header of HTML page. You can’t use header(“Content-type: image/jpeg”); in the middle of file because once you write anything (outputs any character) its header is automatically set to text and once header is set you can’t change it. So, check your file and remove any output before header statement (even tabs and spaces are not allowed).

      • hi sir i am priya i am engineering student
        i doing project of website creation for digital studio
        i put coding for storing and displaying image i use BLOB for storing the image when display
        usin coding
        echo “.row[image].”;
        echo “.row[name].”;
        echo “.row[changes].”;

        but text fields are displayed correctly in but image is displayed as some other strange character

    • Hi Priya,

      Answer to your question is already given in previous comment. To display image with other form data use HTML tables. You can’t display image with other data in top level body of because its header is already set to text/html. That is why you seeing strange characters because browser is displaying image binary data as text.

  21. Hello Vikas,
    thanks for code, its actually working fine. and i am new in php programming. i have a problem, i were saving a image name in db and image save with actual name in specified folder. now what? i want to display all images which names stored in database with resize. i know how to display single image but i don’t know how to resize? please help me…

    • Hello,
      Use HTML img tag and give width and height according to your need. If you want to resize original image then use PHP GD library for this task. Read previous comments for details.

  22. Hi, Vikas I am trying to use your code to store and retrieve image from database but whenever I upload any image, there is a message” s Thank you for submitting” . I checked in code, I am not sending any echo message “s” before “Thank you for submitting” and also whenever I tried to retrieve image there is a message” sPlease use a real id number”. Would you please help me, how could I fix this problem.

    Sanam Maharjan

    • It worked for so many although am getting back the same url with the id number
      i tried the solution above but i think i don’t know how to implement it. i have emailed you my diplay and insert scripts and hope that your can’t help me clean it and verify the problem. Am axiously waiting for your reply. reenez

  23. Thank you very much for this. I do have a question though. A bit of an explination first. I wanted the user to be able to view the picture after upload, so I added a link in the file_insert html section for the user to click on to view the file. Lets say that the file didn’t get uploaded. where would I implement the error code if there was no file. As of right now, my
    link displays no error, just the file path for the image. I am also new to PHP, but understand what’s going on in the code, but don’t see the problem. I know there is no image uploaded yet, but would like an error for just in case a file didn’t get uploaded.

    • I guess I should have typed the link different. the link I have in my code is the “a href=filepath…… that was posted earlier in the comments.

      • Hi Caleb,
        Most of the error code must be in upload function. I edited the file_insert.php file to include some error code to handle most of the common errors. See the modified code, you can add additional code according to your requirement. About displaying image, give link to user on successful image upload. Now you can see id of uploaded file after successful upload. Just convert that message to HTML link.

  24. hii

    Brother I used your code for uploading an Image . But When I run the program I can select an Image to Upload but when I submit the form I got the following Warning .

    Fatal error: Call to undefined function finfo_open() in /var/www/imageupload/file_insert.php on line 47

    function finfo_open is not working for me . Please help me to overcome this

    Thank you.

    • Hi,
      It seems you PHP installation does not have FileInfo module installed. So, upgrade your php to latest version and after that if the module still not works then install it manually.

  25. Dear Sir,
    When i choose the image,the following error are accrued –

    Fatal error: Call to undefined function finfo_open() in C:\wamp\www\music\file_insert.php on line 47

    Plz tell me a solution.

  26. Hello Vikas
    I found this site very use for me.
    Please check out my code to upload a passport and to display it, it does display locally but not on the internet and i don’t know why. i have tried all i could but no success.
    Here is the code

    if(($_FILES[‘pic’][‘tmp_name’]==””) || (!ereg(‘image’,$_FILES[‘pic’][‘type’])) || ($_FILES[‘pic’][‘size’]>50000))
    $message=”Please you have to upload your passport in the format specified”;
    move_uploaded_file($temp_name,$destination) or die(‘The Upload is not successful, Please try again’);
    $sqlimage=”INSERT INTO utme_images (temp_name, image_name) VALUES (‘$temp_name’,’$image_name’)”;
    $sqlquery=mysql_query($sqlimage) or die(mysql_error());
    $sql=”SELECT * FROM utme_images where image_id=’$image_id'”;
    $qry=mysql_query($sql) or die (mysql_error());

    • Hi,
      You have not posted the complete code. The code to display image is missing. Of the code posted, I must say that don’t move the image with $_FILES[‘pic’][‘name’] as name of saved file as users may upload images with same name. So, use some unique identifier as name of image (such as id of sql query, md5 identifier or temp_name may be). And if you are saving image with original name then $imag=$rw[“temp_name”] should be $imag=$rw[“image_name”] to fetch image. Try out and see what happens, if you still faces problems then email me your code.

  27. hello vikas, there is a slight problem regarding the codes above, when i press submit button i get this fatal error:

    Fatal error: Call to undefined function finfo_open() in C:\xampp\htdocs\imageupload\file_insert.php on line 50

    what is the problem there?
    thx sir

  28. hello

    i was try it but there an error
    ” Fatal error: Call to undefined function finfo_open() in C:\AppServ\www\test_image\file_insert.php on line 47 ” and i don’t no what shroud i do ? please help me

    Thank you


  30. ! ) Fatal error: Call to undefined function finfo_open() in C:\wamp\www\mini_image\file_insert.php on line 47
    Call Stack
    # Time Memory Function Location
    1 0.0017 394800 {main}( ) ..\file_insert.php:0
    2 0.0017 394800 upload( ) ..\file_insert.php:23
    this is the error please help me

  31. I’ve made a table in mysql called testimonials where I saved client’s testimonials and their photo in same table. But at the time of retrieving the images with their testimonials I’m unable to do that. I want to display pictures with the testimonial content on a page called testimonials. Everything is working at my end except images are not displaying with each testimonial. Is there anyone can help me out. Its kind of urgent for me.

    • Nobody can help you unless he/she doesn’t knows the cause of your problem. So, explain problem you are facidng in detail (any error you are getting). I advice you to firstly try to display only images (see post for code) and later on display both text and images on same page by using html tables (read other comments).

  32. ( ! ) Warning: finfo_file() expects at least 2 parameters, 1 given in C:\wamp\www\mini_image\file_insert.php on line 47
    Call Stack
    # Time Memory Function Location
    1 0.0021 395968 {main}( ) ..\file_insert.php:0
    2 0.0021 395968 upload( ) ..\file_insert.php:23
    3 0.0031 396832 finfo_file ( ) ..\file_insert.php:47

    ( ! ) Warning: finfo_file() expects parameter 1 to be resource, boolean given in C:\wamp\www\mini_image\file_insert.php on line 50
    Call Stack
    # Time Memory Function Location
    1 0.0021 395968 {main}( ) ..\file_insert.php:0
    2 0.0021 395968 upload( ) ..\file_insert.php:23
    3 0.0038 397040 finfo_file ( ) ..\file_insert.php:50

    Uploaded file is not an image.
    after installing i got this problem please help me

    • Use following code after finfo_open() function to see are you able to get fileinfo resource:
      if (!$finfo) {
      echo “Opening fileinfo failed”;
      If $finfo resource is correctly returned then see mime type of uploaded file with:
      echo finfo_file($finfo, $_FILES[‘userfile’][‘tmp_name’]);

  33. Hi,
    i did try ur code given at the site and others codes as well to show images from database.Bt i m facing a similar problem that my images r being stored in Db bt not showing,only the path is displayed on it and no error???
    please do help as soon as possible

    • Hi,
      There may be many reasons for showing only path instead of image. See below for some reasons:
      1. Incorrect Id. Be sure that you are using correct Id when retrieving the image (which you get upon submitting it using code given).
      2. Image not uploaded successful. Be sure your image data gets saved in database. Use echo statement in display.php for debugging purpose to display image data (comment header statement to verify this). See are you getting a lot of chars as output.
      3. If second step is successful, then restore display.php to normal. Be sure to exactly copy the code of this file. Even a single extra space is harmful and will not let you to see image. Reason is that no output should be sent to web server prior setting header for displaying image, else header is automatically set by web server to text/html and you will not be able to see image.
      I think trying these steps will solve your problem 🙂

  34. The image “http://localhost/dinesh/php-code/img-upload.php” cannot be displayed because it contains errors.

    Sir,I am getting this error for displaying images on my page..Please tell me the solution for this…

  35. Hi Sir, Your tutorial is really helpful for my project . Actually I am working on a project where I need to store the pages of a book in sql database and then wanna retrieve. As per your tutorial we can retrieve by manually changing the (?id=x) .Is there any way where I click on a link suppose (Maths Book) and this should start retrieving the images from the id=1 and giving me an option like next button on which I click and post id changes to id=2 and so on..


    • Hi,
      You question is off-topic. You can achieve what you want to do easily by using JavaScript or Ajax at front-end. Simple fetch images say (1 to 10) on initial request using php limits. Display them one by one as user selects using JavaScript (that reduces delay than retrieving images one by one). Also provide user next button with which next images (10 in this case) are downloaded from server again and so on.

  36. Hello Sir, Please help with this 😦 I have tried many thing but i could not figure out how to do it. I will explain my web (code) then show you what I could not do.
    I have three pages in my web. The first page has a description of graphical password and ask user for information such as email, age, country, gender. By click on button (called register), a php page will be opened to 1- store the previous information in the database and 2- to show a grid of pictures 10 by 10 which is already stored in the database.***** THE USER SHOULD BE ABLE TO SELECT 4 PICTURES AND EACH SELECTED PICTURE ONCE THE USER CLICK ON IT, SHOULD BE APPEAR IN A RAW UNDER OR ABOVE THIS 10 BY 10 PICTURES. AS SOON AS THE USER SELECT 4 PICTURES, A BUTTON CALLED (DONE) WILL BE ACTIVATED AND ABLE TO BE CLICKED****. If it is clicked, another php page will be opened to store the paths of 4 pictures the user selected during the registration the database. Also, to show thank you message for participating.

    I have succeed in doing first page and store its information in the database. Also I managed to show the grid of pictures using their paths stored in the database. The thing that I could not done is above between ***
    I think I have to deal with onclick function and do some AJAX or Javascript. The point is I do not know how to do it.

    Here is my code to show the grid of pictures using their paths stored in the database. If you tell me what to add to make these pictures selectable and able to send what the user selected to the database, this will be very helpful.

    Thank you in advance


    //This gets all the other information from the form

    // Connects to your Database

    $con = mysql_connect("localhost","root", "root");
    if (!$con)
    die('Could not connect: ' . mysql_error());

    mysql_select_db("ImagesOfNationalCultures", $con);

    //Writes the information to the database

    $query1 = "INSERT INTO Users (email, gender, age, country) VALUES ('$email','$gender','$age','$country')";

    $query2 = "SELECT * from Images ORDER BY RAND()";

    $result = mysql_query($query2,$con);
    $i = 0;
    $max_columns = 10;
    echo "”;
    while ($query_row=mysql_fetch_array($result)){

    // open row if counter is zero
    if($i == 0)
    echo “”;
    echo “”;


    echo ”;
    echo “”;

    // increment counter – if counter = max columns, reset counter and close row
    if(++$i == $max_columns)
    echo “”;
    } // end if
    } // end while
    echo “”;


    • Hi,

      Your comment is slightly off-topic so I can’t help you much. But I can give you slight hint. When the user selects the image you can store its identifier in JavaScript array and at the end whem submit button is clicked converts that array values into a single string (delimited by some character) and pass them to server by setting that string to some hidden form field. Thats one simple possible solution.

  37. By the way, I would like the picture itself to be selected NOT to include check box beside each picture in the set.

    Many thanks again

  38. Hi,

    I’ve been able to successfully insert images into a table and then display them, but I was just trying to transfer images from one table into another and haven’t been able to figure it out. Do you know how to do that?

      • Ya, I finally figured out I just needed to addslashes again after I retrieved the image before I could insert it into another table. Thanks.

  39. Hi Mr Vikas
    i have been looking all over the web for these useful php codes but found them here i only encounter a single problem whenever i try to submit and it looks like this
    Fatal error: Call to undefined function finfo_open() in C:\xampp\htdocs\kia\file_insert.php on line 47
    iam trying to design a website for my company but i still face another css problem whenever i try to minimize a window elements overlap other elements i’ve tried dispay:block; but it still fails can you help me out
    Thanks in advance

  40. Hi Sir i can display picture at another page as you describe in above example. Sir but i want to display picture in same page where i insert image or other page included html element and php scripts but face error like modify header so pls help
    thanks Sir.

  41. Hello,

    I have problem when uploading the image…
    when i try to upload the image…

    it says like this

    “The image “http://localhost/up/getImage.php?=1″ cannot be displayed because it contains errors.”

    I do understand and I assume that there is nothing wrong with the uploading code because..
    when i try to cut the header… it will echo unknown binary characters.. therefore that this code is correct and it can talk to mysql….

    So .. what is actually the problem here??

    • Hi,
      Be sure that you are not sending any output (not even space or newline outside php tags) before setting header of webpage. Alternatively, try to display image inside html table cell. If you are successful in doing that then problem is in header of webpage that means webpage got output before setting header mime type. Also, use longblob to store if image of large size (in megabytes).

  42. hello vikas ji,
    i have created form to insert image in mysqldatabase which i got success. the code goes like this


    now the problem is i’m unable to display the images, it does diaply in binay form. ths code goes like this:

    //error reporting(E_ALL);
    //connecing database
    echo mysql_error();
    echo mysql_error();
    // Grab the data from our people table

    $q="SELECT image FROM imagebank";
    //echo $row['id'];
    //echo $row[‘name’];
    header(“Content-type: image/jpeg”);
    echo $row[‘image’];
    echo mysql_error();

    Please help me out, i have to a submit as project.

    Hoping of your prompt response.

    • Hi,
      The reason for seeing binary characters may be because of incorrect header of webpage. Don’t output anything on webpage before setting header. Even a single space outside php tags can result to this. Also, this way you can only display one image (and nothing else) in a page. So to display more images and other data with images use html tables and dispaly image inside table cell.

      • dear sir,
        i applied your above code to display the BLOB type image from my database, it worked after i entered id one after another. now i want to get it displayed in tabulated form. Please help me out. E-mail:

        Thanking your, sir.


  43. Hi,
    I have problem while access data form DB.
    Data type is BLOG and in that field .txt file is uploaded.
    How can i access that txt file.
    Thank You.

  44. First of all, let me say thank you for your wonderful tutorial, I’ve learned a lot so far; however, I’m having an issue.

    The issue I’m having is with an error message regarding the $file_open() function. I have looked for a number of solutions, but haven’t found any. The error I get is:

    Fatal error: Class ‘finfo’ not found in C:\xampp\htdocs\test\file_insert.php on line 50

    I am running PHP 5.3.8 and can’t get the file to call the function. Any advice?

  45. Thank u for this tutorial can anybody in the forum give an php approach on how can I upload image and save it direct to the database.. I was doing a school project on card cataloguing system.. “The situation is this: If input all information about the books in the form I need to upload also an image of the book browse it and select and then save it.. ” How can I do this..? Please help me

  46. Hello Sr i try the code and it work with me in uploading bt when i’m trying to display it it give me this msg

    Please use a real id number .. how to solve it plz

  47. Fatal error: Call to undefined function finfo_open() in C:\wamp\www\example\file_insert.php on line 47
    hi this is the error displayed when am running the codes

  48. Sir i read the above comments and i really dont know how to install finfo_open() module. I am using PHP MY DAmin and using xampp server. could you terll the steps as i ma getting the error

    Fatal error: Call to undefined function finfo_open() in F:\xampp\htdocs\xampp\db\images\file_insert.php on line 47

  49. pls when I executed the code…file_insert.php I got an error. The error is this “fatal error: call to undefined function finfo_open() in c:\wamp\www\practice\file_insert.php on line 47. Pls I need help on the error, because I am new to php and mysql

  50. thanks…I am able to rectify the finfo problem….I enabled it in php extension option of my wamp server…..yea…it is inserting..thanks plenty

  51. hello vikas,
    insert code is working properly now and yes i can open mysql through phpmyadmin,but display image is not working.The error is that:Whenever am running “displayimage” file without taking any input from me only its saying use a real id. So can u tell me what modification i should do.

  52. Hello sir i’m shyam, sir i want to display all the images in php page from mysql, code is also correct but it does not resturn any value, plz help me i have to submit the project within 10 days. I hope that u will sol ve it my code is

    Untitled Document

    am sending u also by mail

  53. Hello sir, sir i want to display all the images but it does not return any image in php page am using wamp server,it returns blank white page plz help me i hate to submit project within 10 days, code is following

  54. Hello vikas,

    Its shruti i executed display image file from think out of box, but its saying PLEASE USE REAL ID ,could u please tell me where i may have gone wrong.I tried all possible way that i can,but ‘m not getting output.Please kindly reply soon

  55. Hello sir, I’m want to display multiple image from mysql to php page in single php page but only one image is displayed , plz help me by giving some code , Thanks in advance.

  56. hello vikas,
    im gettin this error when i submit a image could u help me with this

    Fatal error: Call to undefined function finfo_open() in I:\xampp\htdocs\deeya\file_insert.php on line 48

    • Hi,

      “To use finfo_open() function you need to install FileInfo module of Php”. If you don’t want or was unable to install this module use can another inbuilt php function “mime_content_type()” to check Mime-type. I updated the code and added the line which uses this function. This line is commented in code. So, to use it uncomment the next line after comment
      “//checks whether uploaded file is of image type” and comment the next two lines following that line. I think this will solve your problem.
      Please tell if you have any doubts or need help.


  57. Hello!
    I am trying to use the image uploading code to upload and image to my database but it is showing this error:

    ( ! ) Fatal error: Call to undefined function finfo_open() in C:\wamp\www\upload.php on line 48
    Call Stack
    # Time Memory Function Location
    1 0.0025 706816 {main}( ) ..\upload.php:0
    2 0.0025 706816 upload( ) ..\upload.php:24

    I understand that the function finfo_open() is not defined that is why it is giving this error but I am not sure of how to debug and proceed! Please help me out!

    • Hi,
      As I commented before in number of comments, “To use finfo_open() function you need to install FileInfo module of Php”. If you don’t want or was unable to install this module use can another inbuilt php function “mime_content_type()” to check Mime-type. I updated the code and added the line which uses this function. This line is commented in code. So, to use it uncomment the next line after comment
      “//checks whether uploaded file is of image type” and comment the next two lines following that line. I think this will solve your problem.
      Please tell if you have any doubts or need help.


  58. wen i insert the image i get a disgusting error message like this
    Fatal error: Call to undefined function finfo_open() in C:\wamp\www\image\file_insert.php on line 49

    wats te prob tell pliz

  59. I tried to run the code using wamp server on local host its giving following error
    Fatal error: Call to undefined function finfo_open() in C:\wamp\www\image-exp\file_insert.php on line 49
    if u can , plz solve it ty

    • Hi,
      You can use this code to upload/save videos in database because blob is binary type so you can store any type of data in it. For playing videos, you have to see at some other logic based on method adopted like HTML5 or flash.

  60. Hi. For you guys having issues with finfo_open() function especially those using XAMPP and WAMP; do this:
    Simply edit your php.ini file and uncomment finfo_open.


  61. hello sir… i am sort of new to php scripting and i have being trying to display images from my database using the following code
    mysql_connect("localhost","root","")or die('Connection not established');
    mysql_select_db("test")or die('Database not connected');

    // Grab the data from our people table
    $sql = "select * from tbl_images";

    $result = mysql_query($sql) or die ("Could not access DB: " . mysql_error());

    $imgLocation = " /uploadfile/";

    while ($row = mysql_fetch_array($result))
    $imgName ="image" ;
    $imgPath = $imgLocation . $imgName;

    echo "”;
    echo $row[‘id’] . ” ” . $imgName. “”;

    all iam getting is this and no real images displayed and sometimes i get some funny characters:

    14 image

    15 image

    16 image

    17 image
    with no real images displayed can you help me to have the right syntax for displaying real images and not some funny characters…thank you

    • Hi,
      Seems like images are stored on filesystem and not in database in your case. If this is the case get image name from database, append it after image path and display image using IMG HTML tag.

  62. sir m unable to upload image. when ever i click submit button give a fatal error. the error show like this—-(Fatal error: Call to undefined function finfo_open() in C:\xampp\htdocs\imageupload\file_insert.php on line 49) .

  63. my sir ,i tried to use your php code to insert image and display it on my web page. But,i couldn’t insert image with this code.
    Here is the problem “Fatal error: Call to undefined function finfo_open() in C:\Program Files\xampp\htdocs\rightupload\file_insert.php on line 37”. please help me.

    • Hi,
      To use finfo_open() function you need to install FileInfo module of Php. If you were unable to install this module use can another inbuilt php function “mime_content_type()” to check Mime-type. To use it uncomment the next line after comment
      “//checks whether uploaded file is of image type” and comment the next two lines following that line. I think this will solve your problem.
      Please tell if you have any doubts or need help.


  64. Hi Vikas!
    Your coding is nice!!
    I have problem “Please use a real id number” when running file_display.php. What does it mean? How can I resolve it. Please reply as soon as possible. I am waiting. Thanks!!

  65. Hello Sir,
    Thanks for the code I try this and it’s executing well. But I have some sort of problems I also wanna store some more information from user like date of birth, name etc…. And I am using the code::
    $name = $_POST[‘name’];
    $dob = $_POST[‘dob’];
    in your image coding in upload function but it’s displaying some warning message in include “file_constants.php”; and two notices undefined index in $name = $_POST[‘name’];
    $dob = $_POST[‘dob’];
    And one error in Query: Column count doesn’t match value count at row 1.. I tried a lot to fix this problem but still fail.. Please Sir help me to get out of this problem..

    • Hi,
      Your corresponding form elements should have exact names which you are using in $_POST like “name” and “dob”. To make sure whether you are getting other values or not, you can output whole $_POST variable by using “vardump($_POST);”.
      I can’t comment further without source code. Share your source if you will not be able to solve the problem.

  66. hello sir.,
    what should i do in this error?:
    (Fatal error: Call to undefined function finfo_open() in C:\xampp\htdocs\file_insert.php on line 55 )
    please help me..

  67. Hello again sir,
    I tried the php code to display an image provided by you but there are two warning message with file_constants.php.. And displaying message “please use real id number” instead taking id number from user… I checked the code myself and try to fix the problem but I fail. Please help me with this…..

  68. Hello Sir,
    I am trying to display an image in the thumbnail form from my database and on clicking those thumbnails full image should be displayed. My php code is::

    $query = mysql_query(“SELECT `imgURL` FROM `images` ORDER BY `imgDate` DESC”) or die(mysql_error());
    if(!$query) {
    echo “Cannot retrieve information from database.”;
    } else {
    while($row = mysql_fetch_assoc($query)) {
    echo ” “;

    But it not executing well and images are not displayed in the thumbnail please help me with this….

    • $query = mysql_query(“SELECT `imgURL` FROM `images` ORDER BY `imgDate` DESC”) or die(mysql_error());
      if(!$query) {
      echo “Cannot retrieve information from database.”;
      } else {
      echo “”;
      $count =0;
      while($row = mysql_fetch_assoc($query)) {
      echo “”;
      echo ”

      echo “”;


      echo “”;

  69. Hi,
    nice tutorial and seems like support on different errors is great. Personally i had to use “mime_content_type” function to get it work. I can upload and display jpg, gif extensions, but still can not upload png : “uploaded file is not an image”.
    Any suggestion on that? i would prefer using png type. Php version is 5.2.9 btw.

    best regards and thanks

  70. Hi. I saw your blog and decided to ask if you could with the project I have. I am trying to upload pdf and download pdf using php and mysql. I have written the codes to upload and download. However, when I try to download the pdf files, it shows that is downloaded and when I try to open it, it gives an error: The selected file can not be opened. The codes for downloading is below and I will need your assistance please:

  71. Hi ,
    I am trying to upload the file into the mysql database using the same PHP script as yours “file_insert.php”
    But I am getting following error ”Missing a temporary folder’ (UPLOAD_ERR_NO_TMP_DIR).

    Could you please tell me what settings do I need to made in the php.ini file to resolve this error.


  72. please i need your help with your code, am new to php and just found your site. was trying it out then i met this error and got tied.

    Fatal error: Call to undefined function finfo_open() in C:\xampp\htdocs\glorycorp\nett.php on line 111

    what do i do ???
    thanks a trillion.

  73. please i need your help with your code, am new to php and just found your site. was trying it out then i met this error and got tied.

    Fatal error: Call to undefined function finfo_open() in file_insert.php on line 111

    what do i do ???
    thanks a trillion.

  74. sir i have this problem in your code how it solve
    ==> Fatal error: Call to undefined function finfo_file() in C:\wamp\www\image_upload_database\file_insert.php on line 49

    $finfo = finfo_open(FILEINFO_MIME_TYPE);

  75. Hello sir,
    Firstly thank you for your code. It works perfectly.
    But i need to make an addition. I want to display the image uploaded to a gallery on the HTML page.
    How can I do that?

  76. firstly thanks so much for publishing this code, I am new to php and have an error occurring and am unsure how to fix it, any chance you could help with this please?

    I have saved all the code to my file system and set up the database but when trying to submit an image I get the following error.

    Fatal error: Call to undefined function finfo_open() in /home/nesto387/public_html/file_insert.php on line 49

    line 49 is this $finfo = finfo_open(FILEINFO_MIME_TYPE);

    any help would be greatly appreciated.

  77. Hello sir,
    I tried your code but while executing it,
    it showing a error.
    Fatal error: Call to undefined function finfo_open() in C:\wamp\www\MySQL\file_insert.php on line 52

    pls tell how to resolve it..

  78. Thanks sir,
    i already solved the mime problem.
    just new problem airse while displaying the images..
    i want to know what this code means i mean fromwhere the ID comming in this line..
    if(isset($_GET[‘id’]) && is_numeric($_GET[‘id’]))

  79. How to show the images without giving the Directory path?
    because we are retriving from data base. I only have to see the image by giving the path of my remote folder..
    but i want to access the images without that pats,

  80. fileinfo error solution:

    Windows users: just edit php.ini and uncomment this line:


    Remember to restart Apache for new php.ini to take effect.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s