retrieving then displaying BLOB image

amchugh89
amchugh89 used Ask the Experts™
on
i have a php code that sucessfully uploads image data into my database table.
Now I need to retrieve and display the image on another page. how the heck do I do this.
I've trolled forums but most of them have conflicting or downright incorrect ways to do it.


Heres my code for uploading the stuff to my database (one picture is uploaded into a single row corresponding to the user who updated that photo for there home page)
I am assuming the following code works, because the 'image column is uploaded with a file that is the same # of kB as picture the thing im uploading.

<html>
<head>
  <title> Upload Image </title>
</head>
<body>
   <form action = "upload2.php" method ="POST" enctype ="multipart/form-data">
     File:
     <input type ="file" name = "image"> <input type = "submit" value = "Upload">
     </form>
     <?php
       include "database.php";
       $username = $_COOKIE['ID_my_site'];

   $file = $_FILES['image']['tmp_name'];
   if(!isset($file))
       echo "Select an image";
       else
       {
         $image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
         $image_name = addslashes($_FILES['image']['name']);
         $image_size = getimagesize($_FILES['image']['tmp_name']);

        if($image_size == FALSE)
        echo "Thats not am image.";
        else
        {
         if (!$insert = mysql_query("UPDATE users SET image = '$image'
WHERE username = '$username'"))
        echo "Problem uploading image. Possible that file is too large";
        else
        {
Sucessfully Uploaded!
        }
        }
       }
     ?>

</body>
</html>

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2011
Top Expert 2016

Commented:
Wow, you have a lot of issues here.  Let me see if I can help.  BTW, you seem to have a duplicate copy of this question.  Looks like it somehow got posted twice.

First off, let's get you a competent script for file uploads.  Here is my teaching example.  Please read it over - code, comments and especially read the man pages.  Then post back with any questions.
<?php // RAY_upload_example.php
error_reporting(E_ALL);


// MANUAL REFERENCE PAGES
// http://docs.php.net/manual/en/features.file-upload.php
// http://docs.php.net/manual/en/features.file-upload.common-pitfalls.php
// http://docs.php.net/manual/en/function.move-uploaded-file.php
// http://docs.php.net/manual/en/function.getimagesize.php


// ESTABLISH THE NAME OF THE 'uploads' DIRECTORY
$uploads = 'uploads';

// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT
$max_file_size = '8192000';  // EIGHT MEGABYTE LIMIT ON UPLOADS

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT
$file_exts = array('jpg', 'gif', 'png', 'txt', 'pdf');

// ESTABLISH THE MAXIMUM NUMBER OF FILES WE CAN UPLOAD
$nf = 3;



// THIS IS A LIST OF THE POSSIBLE ERRORS THAT CAN BE REPORTED IN $_FILES[]["error"]
$errors    = array(
    0 => "Success!",
    1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
    2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
    3 => "The uploaded file was only partially uploaded",
    4 => "No file was uploaded",
    6 => "Missing a temporary folder",
    7 => "Cannot write file to disk"
);




// IF THERE IS NOTHING IN $_POST, PUT UP THE FORM FOR INPUT
if (empty($_POST))
{
    ?>
    <h2>Upload <?php echo $nf; ?> file(s)</h2>

    <!--
        SOME THINGS TO NOTE ABOUT THIS FORM...
        NOTE THE CHOICE OF ENCTYPE IN THE HTML FORM STATEMENT
        MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD
        INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN $_FILES ARRAY
    -->

    <form name="UploadForm" enctype="multipart/form-data" action="<?=$_SERVER["REQUEST_URI"]?>" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="<?=$max_file_size?>" />
    <p>
    Find the file(s) you want to upload and click the "Upload" button below.
    </p>

    <?php // CREATE INPUT STATEMENTS FOR UP TO $n FILE NAMES
    for ($n = 0; $n < $nf; $n++)
    {
        echo "<input name=\"userfile$n\" type=\"file\" size=\"80\" /><br/>\n";
    }
    ?>

    <br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <b>overwrite</b> existing files.
    <input type="submit" name="_submit" value="Upload" />
    </form>
    <?php
    die();
}
// END OF THE FORM SCRIPT




else // WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
{

// THERE IS POST DATA - PROCESS IT
    echo "<h2>Results: File Upload</h2>\n";

// ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
//    echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>\n";

// ITERATE OVER THE CONTENTS OF $_FILES
    foreach ($_FILES as $my_uploaded_file)
    {

// SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
        $error_code    = $my_uploaded_file["error"];
        if ($error_code == 4) continue;

// SYNTHESIZE THE NEW FILE NAME
        $f_type    = trim(strtolower(end    (explode( '.', basename($my_uploaded_file['name'] )))));
        $f_name    = trim(strtolower(current(explode( '.', basename($my_uploaded_file['name'] )))));
        $my_new_file = getcwd() . '/' . $uploads . '/' . $f_name .'.'. $f_type;
        $my_file     = $uploads . '/' . $f_name .'.'. $f_type;

// OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
        if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed");

// IF THERE ARE ERRORS
        if ($error_code != 0)
        {
            $error_message = $errors[$error_code];
            die("Sorry, Upload Error Code: $error_code: $error_message");
        }

// GET THE FILE SIZE
        $file_size    = number_format($my_uploaded_file["size"]);

// MOVE THE FILE INTO THE DIRECTORY
// IF THE FILE IS NEW
        if (!file_exists($my_new_file))
        {
            if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
            {
                $upload_success = 1;
            }
            else
            {
                $upload_success = -1;
            }

// IF THE FILE ALREADY EXISTS
        }
        else
        {
            echo "<br/><b><i>$my_file</i></b> already exists.\n";

// SHOULD WE OVERWRITE THE FILE? IF NOT
            if (empty($_POST["overwrite"]))
            {
                $upload_success = 0;

// IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
            }
            else
            {
                $now    = date('Y-m-d');
                $my_bak = $my_new_file . '.' . $now . '.bak';
                if (!copy($my_new_file, $my_bak))
                {
                    echo "<br/><b>Attempted Backup Failed!</b>\n";
                }
                if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
                {
                    $upload_success = 2;
                }
                else
                {
                    $upload_success = -1;
                }
            }
        }

// REPORT OUR SUCCESS OR FAILURE
        if ($upload_success == 2) { echo "<br/>It has been overwritten.\n"; }
        if ($upload_success == 1) { echo "<br/><b><i>$my_file</i></b> has been saved.\n"; }
        if ($upload_success == 0) { echo "<br/><b>It was NOT overwritten.</b>\n"; }
        if ($upload_success < 0)  { echo "<br/><b>ERROR <i>$my_file</i> NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</b>\n"; }
        if ($upload_success > 0)
        {
            echo "$file_size bytes uploaded.\n";
            if (!chmod ($my_new_file, 0755))
            {
                echo "<br/>chmod(0755) FAILED: fileperms() = ";
                echo substr(sprintf('%o', fileperms($my_new_file)), -4);
            }
            echo "<br/><a href=\"$my_file\">See the file $my_file</a>\n";
        }
// END ITERATOR
    }
}

Open in new window

Most Valuable Expert 2011
Top Expert 2016

Commented:
Next let's turn to the issue of the data base.  Please do not put images into a data base.  Just because they have a BLOB data type does not mean that it makes sense to use it to store images.  There are lots of reasons for this, but here are two: performance and ability to backup the data base.  Consider what happens if someone queries, "SELECT * ..." You will do a complete table scan passing all the image files through the data base for every such query.  Trust me, this is not something you want on your resume!

Images belong in a directory of the file system, full stop.  You want to carry the URL for the image in the data base, but not the image file.

When you want to display images from the file system, you use the HTML <img /> tag.  It's that simple :-)

Best regards, ~Ray
Most Valuable Expert 2011
Top Expert 2016

Commented:
Lastly, let's forget about addslashes.  Instead, choose the SQL-appropriate escape function, something like mysql_real_escape_string().  Please read the cautionary notes and recommendations in the description here:
http://us2.php.net/manual/en/function.addslashes.php
Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Author

Commented:
why is there no database queries and stuff. how will i be able to save different images for different users and retrieve later??
Most Valuable Expert 2011
Top Expert 2016
Commented:
You would want to come up with a naming convention that would associate the images with the users.  For example, I use a pattern that adds the DATETIME  to the user id number.  So if today, user #31 uploaded an image the key would look like U31_20100630234257 and the image name would be U31_20100630234257.png

When you want to show all the uploaded images for user #31, you can scan the directory for file names that start with U31_ (or you can use leading zeros on the User Number, so maybe you would use U0000000031_ just in case you had a wildly successful app and you got millions of users).  This scan goes into a PHP array, and you can sort the array.  So long as the User # part of the file name is of a consistent length, the array sort can easily give you the newest or oldest images.

You can use the key as a field in a data base, too.  If the user tagged image U31_20100630234257.png with the name, "Fred", your data base might have an associated pivot table that had a tag field with "Fred" coordinated with that image name.

So to sum up, there are some things that make sense in the data base, some in the file system and some in the PHP code.  The app design coordinates all of these and assigns the appropriate responsibilities to the appropriate technologies.

HTH, ~Ray
MurfurFull Stack Developer
Commented:
I'm SO with Ray on this - while a database CAN store images, it doesn't mean that it SHOULD. Kind of the Jurassic Park DNA splicing issue and you invariably end up with one hell of a Brontosaurus sized problem as your database grows! Bear in mind that when databases were invented by Druids long with Stonehenge, images were not much more than theoretical and it was a case of add a field for other random stuff we might want to add in the future hence it is a BLOB field and not a specific IMAGE field because the Druids soon realised the associated problems and never developed it.

I know of what I speak, too - once burned, twice shy and all that. In my yoof days of learning DBs and code (oh, so very log ago), I thought it was so cool to be able to store thumbnails in the db (I was building a company phone book with faces, client logos etc.) as it meant that I could replicate the whole shabang very easily to another office location with one simple back up. But as the company grew, so did the db except it did so exponentially, as you never really delete records but disable them as customers (hopefully) and employees (sometimes) come back!

What this long diatribe is trying to tell you is that I am rather bored this Thursday morning and wondering where the Sun went. Oh, and I need more coffee too.

But (while the kettle boils), a database storing images becomes large EXTREMELY quickly which affects your speed of any queries and also affects your backup strategy as they are correspondingly ma-hoosive too.

Having the images stored on disk as images gives you so many administrative advantages as a developer/site admin - you can see them, change them, tweak them without affecting the rest of the database or site.

OK, rant over, kettle has boiled and new coffee will be in the cup shortly... :)
Chiming in on this. There are only a few situations where you would actually want to store binary data into a database.

ie: storing sensitive documents, images such as tiff faxes with maybe social security or other personal data. etc etc

And even then it's probably better to secure a server as best you can than store binary data into a dbase. we have one db that does have documents stored in it. and it's pushing 100 gigs of data.

If you do decide to go this route make sure you have the most powerful machine you can afford to buy. Maybe a xeon server of some sort.

Author

Commented:
okay i see where you guys are coming from about why BLOB storage is bad - and Murfur you should write a book on php - who knew a php-db post could be entertaining.

BUT, i have no idea how to implement the alternative method. could you give me code that uses your date time method or some kind of refernces on how to do that.

maybe the code you already gave was just that - but when i run it (upload the files on my page), i get an error message that reads:

"New XAMPP security concept:
Access to the requested object is only available from the local network.
This setting can be configured in the file "httpd-xampp.conf"."

im real confused - i've only been doing php for a month and have never taken a CS class before.

Author

Commented:
whoa Ray i looked you up on google then twitter. i see you live in DC. so do I.

this is kind of creepy but if I rode my bike to your house or something could you like look at my code and my website (its all on my laptop). I've been working on it for about a month now and am almost done.
My site is based off of an idea i had this year at school, but I havent been able to implement it exactly like I wanted to (though I have come pretty close).

I think my idea is kind of good - not completely groundbreaking or anything - but based on what I think is a better way to do some stuff that other sites already do.
maybe you might be interested?

I live in Alexandria by the way and have to go back to Blacksburg for school by July 6 - I would really appreciate your help as it says you are a 'genius' and you sound like one too but I could understand why you, as a genius, might be busy.

my name is Aiden McHugh im on facebook a lot if you could find it in your heart to meet with me then could you message me an place and time?
Most Valuable Expert 2011
Top Expert 2016

Commented:
Hi, Aiden.  The schedule is not real good right now - my son leaves for China on the 4th, so our family is kind of wrapped up in that.  But we could talk by phone.  In the interest of keeping EE involved for the better service of the community, we might want to cross-post our conversations here.  You can call me on 703.346.0600.  If I miss the call, I can call you back.  Best, ~Ray
Most Valuable Expert 2011
Top Expert 2016

Commented:
Probably the most useful advice I offered was here:
ID:33111607

Never heard from the fellow, but our schedules were complicated by travel plans.
Guy Hengel [angelIII / a3]Billing Engineer
Most Valuable Expert 2014
Top Expert 2009

Commented:
This question has been classified as abandoned and is being closed as part of the Cleanup Program.  See my comment at the end of the question for more details.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial