Image file corrupted

Hi,

i have created a File repository to store my .jpg image files in a database called filestore. I can easily store them in my database and can extract the information about the files to be displayed in my browser. Next to each file is a download button, when i try to download the file and try to view it, i get a message from Windows Photo gallery saying:
Photo gallery can’t open this picture or video. The file seems to be damaged or corrupted

 code snippet
if(isset($_GET['action']) and ($_GET['action'] == 'view' or $_GET['action'] == 'download') and isset($_GET['id']) )
{
    include 'db.inc.php';
    $id = mysqli_real_escape_string($link, $_GET['id']);
    
    $sql = "SELECT filename, mimetype, filedata FROM filestore WHERE id ='$id'";
    
    $result = mysqli_query($link, $sql);
    if(!$result)
    {
	$error = 'Database error fetching requested file';
	include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
	exit();
    }
    
    $file = mysqli_fetch_array($result);
    if(!$file)
    {
	$error = 'File with specified ID not found in filestore db';
	include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
	exit();
    }
    
    // Use variables to  send the data in http headers
    $filename = $file['filename'];
    $mimetype = $file['mimetype'];
    $filedata = $file['filedata'];
    $disposition = 'inline'; // use to download
    
    if($_GET['action'] == 'download')
    {
	$mimetype = 'application/octet-stream'; // force download in older browsers
	$disposition = 'attachment';
    }
    
    // Content-type must come before Content-disposition
    header("Content-type: $mimetype"); 
    header("Content-disposition: $disposition; filename=$filename"); // force the browser to display save dialog for download
    header('Content-length: ' . strlen($filedata) );
    
    echo $filedata;
    exit();  
}


what do i need to do to ensure that i can successfully view my image files?

Do you guys think that it would be best to create a PHP file system to manage my image files? If so, would i still need to use my db to store the text string of the file name or a name associatived with the file?

Yes i have had trouble viewing the fies after adjusting the max_allowed_packet size. Although, please bear in mind that i had to adjust this cos i was not able to upload other .jpg’s from my system, i don’t know why but after i adjusted it i was able to upload my other jpg’s. Before and after i adjust the max_allowed variable i still go the error from Windows Photo Gallery.

I also had a gander at the file sizes to see if they were changing after i uploaded my images, but sad to say, there were to same so it did not affect the file sizes after uploading the images, but it was worth a try.

Do you think i should uninstall windows photo gallery perhaps? despite the fact i can view them directly from their original location.

Scallio, assuming that the OP has used the same magicquotes.inc.php file as used in the book:

<?php
if (get_magic_quotes_gpc())
{
    function stripslashes_deep($value)
    {
        $value = is_array($value) ?
                array_map('stripslashes_deep', $value) :
                stripslashes($value);

        return $value;
    }

    $_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
    $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
}
?>

then an issue with strip slashes is unlikely.

@nvidia123

Have you had any trouble viewing files which have been uploaded after you changed the max_allowed_packet setting?

Are the ones that are corrupted ones that were uploaded before or after when you changed the max_allowed_packet setting?

Before, after adjusting the max_allowed_packet variable i still got the error on Windows Photo Gallery. If i go to where the files are store directly on my hardrive before they are uploaded onto the DB, they look absolutely fine, i can veiw them easily.

I think there could be a problem with the download code because uploading the files from my system onto my db works fine so i am guessing there is something i need to add on the download section. What do you thnk?

No i’m afraid not, sorry. 2days ago it was giving me warning’s, MySQL server has gone away - MySQL when i was trying other .JPG’s files but i later fouind out that it had to do with the mysql variable, max_allowed_packet, which essentially has a default of 1mb, so since i am using WAMP server, i went into my.ini file and changed it to 16M. Once changing that it was able to upload other .jpg’s. Does that help perhaps? probably not but i though i would just let you know.

Also a file system maybe better for me BUT since i’m following the book, i would like to finish this chapter and the book using what it i has asked me to do rather than recreate a new file system.

I once attemted to do the same thing but it went wonkers because I applied addslashes() to the image data on INSERT. So if you’re using addslashes() to add the data to the database, don’t :slight_smile:

I would concur. Storing large items in the database eats up performance, and the file system gives you a lot more flexibility to organize your files conveniently and make changes more easily (your OS effectively becomes a high powered viewer and administration system, which you would otherwise have to do without, build, or customize from a vendor, all of which are likely to be more work and produce inferior functionality)

nvidia123, is the script fom Chapter 12 of Kevin Yank’s “Build Your Own Database Driven Website”? If it is the code snipped doesn’t show the end bit where the file is selected (see the last few lines of the code below (as from how it was when I last downloaded the code archive for the book)).

<?php
include_once '../includes/magicquotes.inc.php';

if (isset($_POST['action']) and $_POST['action'] == 'upload')
{
    // Bail out if the file isn't really an upload
    if (!is_uploaded_file($_FILES['upload']['tmp_name']))
    {
        $error = 'There was no file uploaded!';
        include_once '../includes/error.html.php';
        exit();
    }
    $uploadfile = $_FILES['upload']['tmp_name'];
    $uploadname = $_FILES['upload']['name'];
    $uploadtype = $_FILES['upload']['type'];
    $uploaddesc = $_POST['desc'];
    $uploaddata = file_get_contents($uploadfile);

    include 'db.inc.php';

    // Prepare user-submitted values for safe database insert
    $uploadname = mysqli_real_escape_string($link, $uploadname);
    $uploadtype = mysqli_real_escape_string($link, $uploadtype);
    $uploaddesc = mysqli_real_escape_string($link, $uploaddesc);
    $uploaddata = mysqli_real_escape_string($link, $uploaddata);

    $sql = "INSERT INTO filestore SET
            filename = '$uploadname',
            mimetype = '$uploadtype',
            description = '$uploaddesc',
            filedata = '$uploaddata'";
    if (!mysqli_query($link, $sql))
    {
        $error = 'Database error storing file!';
        include_once '../includes/error.html.php';
        exit();
    }

    header('Location: .');
    exit();
}

if (isset($_GET['action']) and
        ($_GET['action'] == 'view' or $_GET['action'] == 'download') and
        isset($_GET['id']))
{
    include 'db.inc.php';

    $id = mysqli_real_escape_string($link, $_GET['id']);

    $sql = "SELECT filename, mimetype, filedata
            FROM filestore
            WHERE id = '$id'";
    $result = mysqli_query($link, $sql);
    if (!$result)
    {
        $error = 'Database error fetching requested file.';
        include_once '../includes/error.html.php';
        exit();
    }

    $file = mysqli_fetch_array($result);
    if (!$file)
    {
        $error = 'File with specified ID not found in the database!';
        include_once '../includes/error.html.php';
        exit();
    }

    $filename = $file['filename'];
    $mimetype = $file['mimetype'];
    $filedata = $file['filedata'];
    $disposition = 'inline';

    if ($_GET['action'] == 'download')
    {
        $mimetype = 'application/octet-stream';
        $disposition = 'attachment';
    }

    // Content-type must come before Content-disposition
    header("Content-type: $mimetype");
    header("Content-disposition: $disposition; filename=$filename");
    header('Content-length: ' . strlen($filedata));

    echo $filedata;
    exit();
}

if (isset($_POST['action']) and $_POST['action'] == 'delete' and
        isset($_POST['id']))
{
    include 'db.inc.php';

    $id = mysqli_real_escape_string($link, $_POST['id']);

    $sql = "DELETE FROM filestore
            WHERE id = '$id'";
    if (!mysqli_query($link, $sql))
    {
        $error = 'Database error deleting requested file.';
        include_once '../includes/error.html.php';
        exit();
    }

    header('Location: .');
    exit();
}

include 'db.inc.php';

$sql = 'SELECT id, filename, mimetype, description
        FROM filestore';
$result = mysqli_query($link, $sql);
if (!$result)
{
    $error = 'Database error fetching stored files.';
    include_once '../includes/includes/error.html.php';
    exit();
}

$files = array();
while ($row = mysqli_fetch_array($result))
{
    $files[] = array(
            'id' => $row['id'],
            'filename' => $row['filename'],
            'mimetype' => $row['mimetype'],
            'description' => $row['description']);
}

include 'files.html.php';
?>

I’m not sure, but


$mimetype = 'application/octet-stream';

might be the problem.
Try commenting that one out and see if works then.

Is php giving any errors at all?

What field type are you using for the field in which you’re storing the files?

I would prefer file system rather than storing image data in the database field. Then there will not be problem.

I located where my images are and tried to open them in paint and i am able to view them fine, but after downloading the file i see the error message. Can somebody help?

Oh yes, the script is directly taken from, Chapter 12 of Kevin Yank’s "Build Your Own Database Driven Website, i chose not add the last few sections because i naturally thought that the issue was with the download section of the code, so my apoligise.
Here is my code copied from the code archive:



include $_SERVER['DOCUMENT_ROOT'] . '/includes/magicquotes.inc.php';
  
if(isset($_POST['action']) and $_POST['action'] == 'upload')
{
    echo 'hi';
    // Bail out if the file is not really an upload
    if(!is_uploaded_file($_FILES['upload']['tmp_name']))
    {
	$error = 'There was no file uploaded';
	
	include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
	exit();
  
    }
    
    // When the form is submitted, store the name in temp variable, orignal name, type, desc and it's mime type
    $uploadfile = $_FILES['upload']['tmp_name'];
    $uploadname = $_FILES['upload']['name'];
    $uploadtype = $_FILES['upload']['type'];
    $uploaddesc = $_POST['desc'];
    $uploaddata = file_get_contents($uploadfile);

    include 'db.inc.php';
    
    // Prepare for user-submitted values for safe database insert
    $uploadname = mysqli_real_escape_string($link, $uploadname);
    $uploadtype = mysqli_real_escape_string($link, $uploadtype);
    $uploaddesc = mysqli_real_escape_string($link, $uploaddesc);
    $uploaddata = mysqli_real_escape_string($link, $uploaddata);
    
    $sql = "INSERT INTO filestore SET
	    filename = '$uploadname', mimetype = '$uploadtype', description = '$uploaddesc', filedata='$uploaddata'";
    if(!mysqli_query($link, $sql))
    {
	$error = 'Database error in storing file!';
	include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
	exit();
    }
    
    header('Location: .');
    exit();
}

// Retrive the file to be downloaded/viewed
if(isset($_GET['action']) and ($_GET['action'] == 'view' or $_GET['action'] == 'download') and isset($_GET['id']) )
{
    include 'db.inc.php';
    $id = mysqli_real_escape_string($link, $_GET['id']);
    
    $sql = "SELECT filename, mimetype, filedata FROM filestore WHERE id ='$id'";
    
    $result = mysqli_query($link, $sql);
    if(!$result)
    {
	$error = 'Database error fetching requested file';
	include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
	exit();
    }
    
    $file = mysqli_fetch_array($result);
    if(!$file)
    {
	$error = 'File with specified ID not found in filestore db';
	include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
	exit();
    }
    
    // Use variables to  send the data in http headers
    $filename = $file['filename'];
    $mimetype = $file['mimetype'];
    $filedata = $file['filedata'];
    $disposition = 'inline'; // use to download
    
    if($_GET['action'] == 'download')
    {
	$mimetype = 'application/octet-stream'; // force download in older browsers
	$disposition = 'attachment';
    }
    
    // Content-type must come before Content-disposition
    header("Content-type: $mimetype"); 
    header("Content-disposition: $disposition; filename=$filename"); // force the browser to display save dialog for download
    header('Content-length: ' . strlen($filedata) );
    
    echo $filedata;
    exit();  
}

if(isset($_POST['action']) and $_POST['action'] == 'delete' and isset($_POST['id']))
{
    include 'db.inc.php';
    $id = mysqli_real_escape_string($link, $_POST['id']);
    
    $sql = "DELETE FROM filestore WHERE id ='$id'";
    if(!mysqli_query($link, $sql))
    {
	$error = 'Database error deleting requested file';
	include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
	exit();
    }
    
    header('Location: .');
    exit();
}

include 'db.inc.php';


$sql = 'SELECT id, filename, mimetype, description FROM filestore';
$result = mysqli_query($link, $sql);
 if(!$result)
 {
    $error = 'Database error fetching stored files';
   include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
	exit();
 }
 
 
 $files = array();
 while($row = mysqli_fetch_array($result) )
 {
    $files[] = array('id' => $row['id'], 'filename' => $row['filename'], 'mimetype' => $row['mimetype'],
		     'description' => $row['description']);
 }
include 'files.html.php';
?>

ScallioXTX, i commented out that line of code u instructed, but no luck i’m afraid, still i get the same error message on windows photo gallery