1

here is the code for my upload.. but it doesn't work.. I've used a file_get_contents function.. Upload image

</head>
<body>
    <form action="upload1.php" method="POST" enctype="multipart/form-data">
    File: 
    <input type="file" name="image"/> 
    <input type="submit" value="Upload image" />

    </form>

<?php 

//connect to the database
$con = mysql_connect("localhost","root", "");
if(!$con)
 {
 die('Could not connect to the database:' . mysql_error());
 echo "ERROR IN CONNECTION";
}

mysql_select_db("imagedatabase", $con);


//file properties

 echo $file = $_FILES['image']['tmp_name']; 
 echo '<br />';

 if(!isset($file))
echo "Please select an image";

else
{
$image = file_get_contents($_FILES['image']['tmp_name']);
echo $image_name = addslashes($_FILES['image']['name']); echo '<br \>';
echo $image_size = getimagesize($_FILES['image']['tmp_name']);

if($image_size == FALSE)
    echo "That's not an image";
    else
{
        $insert = mysql_query("INSERT INTO images (image) VALUES    ($image)",$con);
if(!$insert)
    echo "Problem uploding the image. Please check your database";  
else 
{
    $last_id = mysql_insert_id();
    echo "Image Uploaded. <p /> Your image: <p /><img src=display.php?        id=$last_id>";
    }
}

}
mysql_close($con);
?>

</body>
</html>

and the code for the retrieve/display goes this way..

<?php
 //connect to the database
 mysql_connect("localhost","root", "") or die(mysql_error());
 mysql_select_db("mydb") or die(mysql_error());

 //requesting image id

 $id = addslashes($_REQUEST['id']);

$image = mysql_query("SELECT * FROM images WHERE id = $id");
$image = mysql_fetch_assoc($image);
$image = $image['image'];

header("Conten-type: image/jpeg");

 echo $image;


 mysql_close($connect);
 ?>

I've created a database named 'imagedatabase' and a table

linuxeasy
  • 6,269
  • 7
  • 33
  • 40
SimonCode
  • 77
  • 2
  • 3
  • 10
  • the database is imagedatabase the table is images the columns inside it is id -autoincrement, name - varchar, image - blob.. please help .. im confused – SimonCode Jan 04 '12 at 08:02
  • What is it exactly that does not work? Do you have any error messages? Be more precise... – Bas Slagter Jan 04 '12 at 08:03
  • 1
    This has been answered on: http://stackoverflow.com/questions/1636877/how-can-i-store-and-retrieve-images-from-a-mysql-database-using-php – Raul Marengo Jan 04 '12 at 08:05
  • use fread() to read byte to byte – Egor Sazanovich Jan 04 '12 at 08:07
  • the problem is the image doesn't upload to the database even though the query is correct. please help. – SimonCode Jan 04 '12 at 08:08
  • **Be careful** your code allows a *blind sql injection*! You have to parse the `$id`! Also remember that no code is executes after a `die` or `exit`. – rekire Jan 04 '12 at 19:39

3 Answers3

8

That's a bad idea to store an image in database. Store a path to it in database, close directory with images via .htaccess and use it on a hard drive.


Why You shouldn't store files in DB?

If You'll use DB to store images You will have:

  1. slow queries
  2. catastrophic indexes' size
  3. high load on bridge php<->mysql
  4. problems with edit photos(You'll need to get image, modify something and insert all data again. Ohh nooo)
  5. problems with transfer files from one place to another
  6. new question on StackOverflow «How to work with files if them not files, but a string»
Egor Sazanovich
  • 4,979
  • 5
  • 23
  • 37
  • the problem is the image doesn't upload to the database even though the query is correct. please help. – SimonCode Jan 04 '12 at 08:08
  • Check your `$_FILES['image']['error'] and type of field in table. Maybe You try to insert too many data to field, which can accept something small? Set it to BLOB – Egor Sazanovich Jan 04 '12 at 08:13
  • @simonjoloburi when you use a database you use a hard drive. You are really making things difficult for yourself. Still, check your logs and try to find an error, there must be one if this isn't working. Otherwise, check your database and see if any records have been created. – Raul Marengo Jan 04 '12 at 08:15
  • @simonjoloburi also, check the comment I made on your question and follow the link, the first answer has a clear script to load images to db. – Raul Marengo Jan 04 '12 at 08:17
  • If You'll use DB to store images You will have: 1) slow queries 2) catastrophic indexes' size 3) high load on bridge php<->mysql 4) problems with edit photos(You'll need to get image, modify something and insert all data again. Ohh nooo) 5) problems with transfer files from one place to another 6) new question on StackOverflow «How to work with files if them not files, but a string» – Egor Sazanovich Jan 04 '12 at 08:19
  • @Ramengo what I mean is that I want to try to store it in a database first.. I will apply the one you meant later.. – SimonCode Jan 04 '12 at 08:29
  • @EgorSazanovich I've used blob.. :) – SimonCode Jan 04 '12 at 08:30
  • @simonjoloburi well, unless you provide some errors or more information on the behaviour, it will be hard to help you achieve this. If you want this to go anywhere, you are going to have to do some digging, check your logs, check your database... troubleshoot your script in simple terms. – Raul Marengo Jan 04 '12 at 08:34
  • ok. 1) Check is Your file ready to be inserted: echo strlen($image); 2) try to insert result of echo $image; manually (through phpMyAdmin or something like this) 3) try to add ' to your query: `INSERT INTO images (image) VALUES ('$image')` – Egor Sazanovich Jan 04 '12 at 08:35
  • @EgorSazanovich I did it already.. but still nothing happens.. it always prompts there was a problem in the database upload.. – SimonCode Jan 04 '12 at 08:44
  • @Ramengo I put an error message when its time to upload the image for checking and it prompts it everytime i try to upload an image.. I followed the link you gave me and to my surprise I did the same thing as what the link instructed. Still the error is that the image can not be uploaded.. is it about the function file_get_contents? – SimonCode Jan 04 '12 at 08:50
  • Have you tried inserting some random text to check whether there is a problem with the actual database? – Raul Marengo Jan 04 '12 at 08:52
  • @Ramengo actually i used another code for the upload,, it uses the fread(); function and it uploads the image to the same database im using.. i want to understand what the heck is wrong with this code when its suppose to really work? :( – SimonCode Jan 04 '12 at 08:59
1

You should save the files in some folder during the upload process and save the name of file in database, so later you can call the name of file from database and link it as a hyperlink to download, i am using the following code to upload images in a folder called files and saving the name of files in database. At the end i have the file name in variable $newname

if ($_FILES['file']['name']) {

    $allowedExts = array("gif", "jpeg", "jpg", "png");
    $temp = explode(".", $_FILES["file"]["name"]);
    $extension = end($temp);
    if ((($_FILES["file"]["type"] == "image/gif")
            || ($_FILES["file"]["type"] == "image/jpeg")
            || ($_FILES["file"]["type"] == "image/jpg")
            || ($_FILES["file"]["type"] == "image/pjpeg")
            || ($_FILES["file"]["type"] == "image/x-png")
            || ($_FILES["file"]["type"] == "image/png"))
        && ($_FILES["file"]["size"] < 500000)
        && in_array($extension, $allowedExts)
    ) {
        if ($_FILES["file"]["error"] > 0) {
            echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
        } else {
            $ext = end(explode(".", $_FILES["file"]["name"]));
            $filename = current(explode(".", $_FILES["file"]["name"]));
            $newname = $filename . '_' . time() . '.' . $ext;
            move_uploaded_file($_FILES["file"]["tmp_name"],
                "files/" . $newname);
        }
    } else {
        echo "<div class='alert alert-success'>Image type or size is not valid.</div>";
    }
}
Shairyar
  • 3,268
  • 7
  • 46
  • 86
0

Uploading images directly into database is not a good idea. Instead upload photos in a folder and then just insert the photo name into the database and then call it later whenever you need. You could try the following Code if you want.

To make the code work for you you have to follow these steps:

  1. Inside the code Replace "your_photo" with your input name (which case I guess it would be "image")

  2. Create a folder where you will be uploading images and then Make changes in->> $newname="support/images/profile/" here write your image folder name

  3. write the proper database query. and remember that the image name will be automatically created and the name stays inside this variable-> $image_name . When you insert the name into database just use $image_name as value.

Upload Script:

 <?
 // If Everything is good- process the form - write the data into the database

$photo=$this->input->post('your_photo');
if($photo==NULL){$image_name='0';}// if no photo is selected the default value of the photo would be 0

    //photo upload starts
        $errors=0;
        if($_FILES['your_photo']){
        $image=$_FILES['your_photo']['name'];
        if($image) {
        define ("MAX_SIZE","100"); 
        function getExtension($str) {   
        $i = strrpos($str,".");
        if (!$i) { return ""; }
        $l = strlen($str) - $i;
        $ext = substr($str,$i+1,$l);
        return $ext; }


        //reads the name of the file the user submitted for uploading
        $image=$_FILES['your_photo']['name'];                                   
        //if it is not empty
        if ($image) 
        {                               
        //get the original name of the file from the clients machine
        $filename = stripslashes($_FILES['your_photo']['name']);
        //get the extension of the file in a lower case format
                                $extension = getExtension($filename);
                                $extension = strtolower($extension);
                                //if it is not a known extension, we will suppose it is an error and will not  upload the file,  
                                //otherwise we will do more tests
                                if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
                                {           
                                //print error message
                                $msg="Sorry! Unknown extension. Please JPG,JPEG,PNG and GIF only ";
                                $errors=1;

                                }
                                else
                                {
                                //get the size of the image in bytes
                                //$_FILES['image']['tmp_name'] is the temporary filename of the file
                                //in which the uploaded file was stored on the server
                                $size=filesize($_FILES['your_photo']['tmp_name']);                              
                                //compare the size with the maxim size we defined and print error if bigger
                                if ($size < MAX_SIZE*1024)
                                {
                                //we will give an unique name, for example the time in unix time format
                                $image_name=time().'.'.$extension;
                                //the new name will be containing the full path where will be stored (images folder)                                                        
                                $newname="support/images/profile/".$image_name;                                                     
                                //we verify if the image has been uploaded, and print error instead                                                     
                                $copied = copy($_FILES['your_photo']['tmp_name'], $newname);                                                        
                                if (!$copied)                                                       
                                {                                                       
                                $msg="Sorry, The Photo Upload was unsuccessfull!";                                                          
                                $errors=1;                                                          
                                }                                                         
                                }                                               
                                else                                            
                                {       
                                $msg="You Have Exceeded The Photo Size Limit";          
                                $errors=1;                              
                                }                                           
                                }}}                                             

                                /*Image upload process ends here- If any problem occurs it will display error message via the $msg, 
                                 otherwise it will upload the image to the image folder. To insert the photo into database $image_name has been used*/ 

                    }


                    if(($_FILES['your_photo'])&& ($errors))/* If any photo is selected and any problem occurs while uploading it will
                                                                display an error message, otherwise transfer the data to Mod_addstudent model  */
                                        { 

                                echo $msg;


                                        }

                    else        {   

                                    //Insert into database.Just use this particular variable "$image_name" when you are inserting into database

                                        $sql="INSERT INTO your_table (field1, your_image_field) VALUES ('','$image_name')"; 




                                }
                ?>

And then to view the image::

   <?php 

 // Retrieve information from Database First and then .. 

if (empty($your_photo))

{ $image_location="images/avatar.jpg";} //if there is no image in database  

 else {$image_location="images/$your_photo";} // if there is any image in database

?>  



  <img src="<?php echo base_url(); ?><?php echo $image_location ;?>" width="150" height="170" />
black_belt
  • 6,601
  • 36
  • 121
  • 185
  • hey @Srijon thanks for the code.. I'll try this one.. I just had a confirmation that we could use the server as our storage for the images. thanks so much.. we are doing our thesis. :D – SimonCode Jan 04 '12 at 10:46
  • exccuse me sir, but the code you gave me is not working.. hehehe.. I followed your steps that you told me but when the form goes to the upload.php it displays the whole code. why is that? – SimonCode Jan 05 '12 at 15:42
  • there is an error.. here.. Fatal error: Using $this when not in object context in C:\XAMP\xampp\htdocs\gallery\gallerysamp.php on line 4 – SimonCode Jan 05 '12 at 15:44
  • Hi, SimonCode. I am sorry it didn't work. But I am sure this time it will. I have created a complete image upload script for you and it is 100% working. Here is the link: http://www.mediafire.com/?vy5dx9ldxwsdyqc Download it . The script is almost ready.. all you need to do is create a new table(table field should be-> id and image) and provide your db connection details. But before you proceed read the read me file first. I hope this time it will work. Let me know how it goes.. cheers :) – black_belt Jan 05 '12 at 18:00