Solved

Upload images to a MySQL database (PHP) doesn't work in IE 8

Posted on 2011-03-06
6
628 Views
Last Modified: 2012-05-11
So I was testing out the insert image code from : http://cookbooks.adobe.com/post_Upload_images_to_a_MySQL_database__PHP_-16609.html

It works great in IE 6 and IE 7, but not in IE 8.

Here is the code:

<?php define ('MAX_FILE_SIZE', 1024 * 50); ?>
<?php require_once('Connections/testConn.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "uploadImage")) {
  
  // make sure it's a genuine file upload
  if (is_uploaded_file($_FILES['image']['tmp_name'])) {
  
	// replace any spaces in original filename with underscores
	$filename = str_replace(' ', '_', $_FILES['image']['name']);
	// get the MIME type
	$mimetype = $_FILES['image']['type'];
	if ($mimetype == 'image/pjpeg') {
		$mimetype= 'image/jpeg';
	}
	// create an array of permitted MIME types
	$permitted = array('image/gif', 'image/jpeg', 'image/png');
	
	// upload if file is OK
	if (in_array($mimetype, $permitted) 
		&& $_FILES['image']['size'] > 0 
		&& $_FILES['image']['size'] <= MAX_FILE_SIZE) {
	  switch ($_FILES['image']['error']) {
		case 0:
		  // get the file contents
		  $image = file_get_contents($_FILES['image']['tmp_name']);
		  // get the width and height
		  $size = getimagesize($_FILES['image']['tmp_name']);
		  $width = $size[0];
		  $height = $size[1];

  
  $insertSQL = sprintf("INSERT INTO images (filename, mimetype, caption, image, width, height) VALUES (%s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($filename, "text"),
                       GetSQLValueString($mimetype, "text"),
                       GetSQLValueString($_POST['caption'], "text"),
                       GetSQLValueString($image, "text"),
                       GetSQLValueString($width, "int"),
                       GetSQLValueString($height, "int"));

  mysql_select_db($database_testConn, $testConn);
  $Result1 = mysql_query($insertSQL, $testConn) or die(mysql_error());
		  if ($Result1) {
			$result = "$filename uploaded successfully.";
		  } else {
			$result = "Error uploading $filename. Please try again.";
		  }
		  break;
		case 3:
		case 6:
		case 7:
		case 8:
		  $result = "Error uploading $filename. Please try again.";
		  break;
		case 4:
		  $result = "You didn't select a file to be uploaded.";
	  }
	} else {
	  $result = "$filename is either too big or not an image.";
	}
  }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>File upload to database</title>
</head>

<body>
<?php
// if the form has been submitted, display result
if (isset($result)) {
  echo "<p><strong>$result</strong></p>";
  }
?>
<form action="<?php echo $editFormAction; ?>" method="POST" enctype="multipart/form-data" name="uploadImage" id="uploadImage">
    <p>
		<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_FILE_SIZE; ?>" />
        <label for="image">Upload image:</label>
        <input type="file" name="image" id="image" /> 
    </p>
    <p>
      <label for="caption">Caption:</label>
      <input type="text" name="caption" id="caption" />
    </p>
    <p>
        <input type="submit" name="upload" id="upload" value="Upload" />
    </p>
    <input type="hidden" name="MM_insert" value="uploadImage" />
</form>
</body>
</html>

Open in new window

0
Comment
Question by:jbrich01
  • 2
  • 2
  • 2
6 Comments
 
LVL 76

Expert Comment

by:arnold
Comment Utility
how big was the file?
MAX_FILE_SIZE is defined as 50k.

You do not have a check on the size of a file.
0
 

Author Comment

by:jbrich01
Comment Utility
Hey Arnold,

Sorry for the delayed response, I had a migraine today.  I've tried it with a file that was 48k as well as with one that was 500k.  neiter worked.  However, I will increase the size to 1024*720 permanently.
0
 
LVL 76

Expert Comment

by:arnold
Comment Utility
echo out to a file the contents of $insertSQL after line 76 and see how the information between 6,7 and 8 differ.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
Comment Utility
When you say "not in IE8" - what happens?  Do you have any error messages?  Have you used var_dump($_FILES) to be sure you are getting the expected information into the PHP script?

Maybe it does not matter to you because you have only very light data requirements, but I'd like to gently suggest that a data base is a terrible place to store images.  You will find that the professionals recommend to store images in the file system and keep the URL of the image in the data base (along with the other pieces of related information).  Some of the reasons for this include performance and backup.  Consider what happens when someone writes a table scan query that says, "SELECT * FROM..." -- the DB engine will have to transfer every image file!

You might also want to reconsider whether there are any images as small as 50K any more.  I took some photos of a baseball game over the weekend and the smallest image I recorded was about 5,000,000 bytes - two orders of magnitude larger than 50K.

This script teaches how to upload a group of images.  Please read it over carefully -- code, comments and especially the man page references.  If you follow the principles here you will have no trouble getting the upload to work.

Best regards, ~Ray
<?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


// PHP 5.1+  SEE http://us3.php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set('America/Chicago');

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

// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 8 MB
$max_file_size = '8192000';

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

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

// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$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"
, 5 => "UNDEFINED ERROR"
, 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...
        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
        ABSENCE OF ACTION= ATTRIBUTE IN FORM TAG CAUSES POST TO SAME SCRIPT
    -->

    <form name="UploadForm" enctype="multipart/form-data" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $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 <strong>overwrite</strong> existing files.
    <input type="submit" value="Upload" />
    </form>
    <?php
    die();
}
// END OF THE FORM SCRIPT



// WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
else
{
    // 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"]);

        // IF THE FILE IS NEW (DOES NOT EXIST)
        if (!file_exists($my_new_file))
        {
            // IF THE MOVE FUNCTION WORKED CORRECTLY
            if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
            {
                $upload_success = 1;
            }
            // IF THE MOVE FUNCTION FAILED
            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/><strong>Attempted Backup Failed!</strong>\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/><strong>$my_file</strong> has been saved.\n"; }
        if ($upload_success == 0) { echo "<br/><strong>It was NOT overwritten.</strong>\n"; }
        if ($upload_success < 0)  { echo "<br/><strong>ERROR: $my_file NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</strong>\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 FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE
    }
}

Open in new window

0
 

Author Comment

by:jbrich01
Comment Utility
Hey Arnold, OK, echo out that line in 6,7, and 8.

Hi Ray, what I mean is that in IE 8 it does not do anthing.  No error messages, and it does not post to the DB.  But in IE 6 it actually shows up in the DB and it the images shows on the display page.

Also, thanks for the suggestion regarding uploading the images in a file system. I started that process and had some trouble with the display page (it was showing all of the images at once instead of one at a time).  So while looking for a solution, I found this link, and I changed my strategy.

http://www.phpriot.com/articles/images-in-mysql/2

They suggested that it was best to save the images in a DB because of:

  ¦ Referential integrity
  ¦ Ease of backup
  ¦ Saving of Inodes
  ¦ Easy categorisation
  ¦ Central point of operations

But, because of all of the reasons you said, I felt it was better to do develop a file system and store the URL and info in the DB.

Thank you for the code above.  And your detailed commenting.  This will really help me to understand the process.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Thanks for the points - it;s a great question, ~Ray
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

As a database administrator, you may need to audit your table(s) to determine whether the data types are optimal for your real-world data needs.  This Article is intended to be a resource for such a task. Preface The other day, I was involved …
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now