Jump to content

Image doesn't display on page PHP/mySQL


Helixia

Recommended Posts

Hello everyone,

 

I'm pretty new to PHP and i don't have much experience.

 

I fellowed a tutorial: Uploading/Storing an Image inside a MySQL Database on Youtube.

 

The code is working, it stores the image in the database, but displaying the image is the problem.

There's only a small gray box when i click it in the browser "view image" it says there is a problem in the image.

The image is saved as a BLOB.

 

My code:

image.php

    <html>
        <head>
            <title>Afbeelding uploaden</title>
        </head>
        <body>
            <form action="afbeelding.php" method="POST" enctype="multipart/form-data">
                Bestand: <input type="file" name="afbeelding">
                <input type="submit" value="Upload">
            </form>
            
            <?php
                include'connectland.php';
                
                //eigenschappen
                $file = @$_FILES['afbeelding']['tmp_name'];
                            
                if (!isset($file)) {
                    echo "Selecteer een afbeelding.";
                } else {
                    $image = addslashes(file_get_contents($_FILES['afbeelding']['tmp_name']));
                    $image_name = addslashes($_FILES ['afbeelding']['name']);
                    $image_size = getimagesize($_FILES['afbeelding']['tmp_name']);
                    
                    if ($image_size == FALSE) {
                        echo "Dit is geen afbeelding";
                    } else {
                        if (!$insert = mysql_query("INSERT INTO afbeeldingen VALUES ('','$image_name','$image')")) {
                            echo "Probleem met uploaden van afbeelding.";
                        } else {
                            $lastid = mysql_insert_id();
                            echo "Afbeelding geüploadt. <p />De afbeelding:<p /><img src=get.php?id=$lastid>";
                        }
                    }
                }
            ?>
        </body>
    </html>

 

get.php

    <?php
        include'connectland.php';
        
        $id = addslashes($_REQUEST['id']);
        
        $image = mysql ("SELECT * FROM afbeeldingen WHERE id=$id");
        $image = mysql_fetch_assoc($image);
        $image = $image['data'];
        
        header ("Content-type:image/jpeg");
        
        echo $image;
    ?>

 

I tried to change Conten-type:image/jpeg to image/png (because it was a png image), but i got the same result.

 

Or are there any better suggestions to do this?

Link to comment
Share on other sites

Although I personally store the images in a folder and simply put the image name in the database, you may want to check this link (note they use 2 files to display the image) http://www.techcubetalk.com/2009/01/tutorial-on-how-to-store-images-in-mysql-blob-field/

 

 

Also, very bad habit to use the same variable for 3 different purposes

 

        $image = mysql ("SELECT * FROM afbeeldingen WHERE id=$id");
        $image = mysql_fetch_assoc($image);
        $image = $image['data'];

maybe...

        $query = "SELECT * FROM afbeeldingen WHERE id='$id'";
        $result = mysql_query($query);
        $row  = mysql_fetch_array($result);
        $image = $row['data'];

Link to comment
Share on other sites

I agree with litebearer all the way. 99.98% of the time its not the best idea to store an actual image inside your database. Databases are using for sorting, storing, and organizing data and information. Filesystems are better used to store and organize actual files.

I would upload/move the file from its original location to a specific location on your server/localhost. Store the path to where you are moving the image in the database along with the file name.

 

Also agree with litebearer on its not good to use the same variable like you did, litebearer's method was the direction to go.

 

I also saw in your PHP code that you used $_REQUEST to get an ID of something. $_REQUEST can cause problems and can also be a security hole as the $_REQUEST array can store values from $_POST, $_GET, and $_COOKIE variables. So if later down the road you accidentally or do use $_POST['id'] AND $_GET['id'] the value that $_REQUEST stores is the last post or get to store its value. In your html form you set the method to POST so stick with getting data using the $_POST variable. For more specifics on this you can google it and some good sources for information will come up.

 

Hope this helped!

Link to comment
Share on other sites

You should use mysql_real_escape_string rather than addslashes. From the manual

http://php.net/manual/en/function.mysql-real-escape-string.php

If binary data is to be inserted, this function must be used.

 

I don't have anything against storing binary data in MySQL, especially for smaller projects. Get into the million rows range, and things like corrupted tables, repairing, and restoring from backups become time-consumers. Using foreign keys, deleting a user, and all pictures associated with her can be done in a single query. From what I understand, Flickr stores their images in a MySQL database.

 

Using $_REQUEST isn't a security issue, but you're correct about it's potential to cause conflicts that aren't obvious to debug.

 

 

Link to comment
Share on other sites

I fellowed the tips of litebearer thank you, but the code from the link didn't work either.

 

I tried to debug it, but when i want to display the image i just got a blank page with nothing into the source code.

I saw in my adres bar the id of the uploaded image like i had before.

 

@algidDes702 What you said about $_REQUEST i didn't know that.

 

@xyph I'm now using mysql_real_escape_string ().

 

the files i have from tutorial are:

 

form:

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>
<HTML>
<HEAD>
	<TITLE> Image Upload to BLOB field </TITLE>
</HEAD>

<BODY>
	<FORM NAME="f1" METHOD="POST" ACTION="upload.php" ENCTYPE="multipart/form-data">
	<table>
		<tr><td> Image Upload Page </td></tr>
		<tr><td> <input type="file" name="imgfile"/></td></tr>
		<tr><td> <input type="submit" name="submit" value="Save"/> </td></tr>
	</table>
	</FORM>
</BODY>
</HTML>

 

Upload.php

<html>
<head>
</head>
<body>
<?php
include "dbconfig.php";

$dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die("Error Occurred-”.mysql_error()");
mysql_select_db($dbname, $dbconn) or die("Unable to select database");

if(isset($_POST['submit']) && $_FILES['imgfile']['size'] > 0) {
        $fileName = $_FILES['imgfile']['name']; // image file name
        $tmpName = $_FILES['imgfile']['tmp_name']; // name of the temporary stored file name
        $fileSize = $_FILES['imgfile']['size']; // size of the uploaded file
        $fileType = $_FILES['imgfile']['type']; // file type

        // $fp                    = fopen($tmpName, 'rb'); // open a file handle of the temporary file
        $imgContent  = file_get_contents($tmpName); // read the temp file
	$imgContent2=base64_encode($imgContent);
        // fclose($fp); // close the file handle

        $insert = mysql_query ("INSERT INTO img_tbl (img_name, img_type, img_size, img_data)
                        VALUES ('$fileName', '$fileType', '$fileSize', '$imgContent2')");

        $imgid = mysql_insert_id(); // autoincrement id of the uploaded entry
        mysql_close($dbconn);

        echo "<br>Image successfully uploaded to database<br>";
        echo "<a href=viewimage.php?id=$imgid>View Image</a>"; 
	}else{
		die("You have not selected any image");
	}
?>
</body>
</html>

 

viewimage.php

<html>
<head>
</head>
<body>
<?php
if(isset($_POST['id']))
{
   // get the file with the id from database
      include "dbconfig.php";
      $dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die("Error Occurred-".mysql_error());
      mysql_select_db($dbname, $dbconn) or die("Unable to select database");

      $id    = $_POST['id'];
      $query = "SELECT 'img_name', 'img_type', 'img_size', 'img_data'
                       FROM img_tbl WHERE id = '$id'";

      $result = mysql_query($query) or die(mysql_error());
      list($name, $type, $size, $content) = mysql_fetch_array($result);

      header("Content-length: $size");
      header("Content-type: $type");
      print base64_decode($content);

      mysql_close($dbconn);
}
?>
</body>
</html>

 

showimage.php

<html>
<head>
</head>
<body>
<?php
    include "dbconfig.php";
    $dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die("Error Occurred-".mysql_error());
    mysql_select_db($dbname, $dbconn) or die("Unable to select database");

    $query = "SELECT 'id', 'img_name', 'img_type', 'img_size', 'img_data'
                     FROM img_tbl ORDER BY 'id'";

    $result = mysql_query($query) or die('Error, query failed');

    while($row = mysql_fetch_array($result)){
               echo "<img src=viewimage.php?id=$row[id] /> <br/>";
    }

    mysql_close($dbconn);
?>
</body>
</html>

Link to comment
Share on other sites

You don't have mysql_real_escape_string() once in your posted code.

 

Nor do you check if your query actually succeeded.

 

We're not here to guide you through a tutorial. If you want to learn, I'll help, but we're going to start with that you know, not what you can copy from a tutorial.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.