Avg. Rating 5.0

Problem

I want to insert code so a file field can be used to upload images. Also, is it possible to upload images to an image placeholder?

Solution

Uploading images with PHP is relatively easy. For security reasons, you should always check that the file is an image, and that it doesn't exceed a maximum size. The original question posed by Daniel Hogg specified that the image should be uploaded to an image placeholder. As long as the image has the same name as the placeholder, the following solution should work.

Detailed explanation

To upload an image (or any other file), you need to create a form with a file field, and set its method to POST. It's also recommended that you include a hidden field with the name MAX_FILE_SIZE, and set its value to the maximum permitted size (in bytes) of the file to be uploaded. This hidden field must come before the file field. Otherwise it won't work. The following code shows a basic upload form:

<form action="" 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>
  <input type="submit" name="upload" id="upload" 
value="Upload" />
</p>
</form>

The form's action attribute has been left empty. This means the script that processes the upload goes above the web page's DOCTYPE declaration. The processing script begins by defining the value of MAX_FILE_SIZE, and looks like this:

<?php
// define a constant for the maximum upload size
define ('MAX_FILE_SIZE', 1024 * 50);

if (array_key_exists('upload', $_POST)) {
  // define constant for upload folder
  define('UPLOAD_DIR', '/path/to/images/');
  // replace any spaces in original filename with underscores
  $file = str_replace(' ', '_', $_FILES['image']['name']);
  // create an array of permitted MIME types
  $permitted = array('image/gif', 'image/jpeg', 'image/pjpeg',
'image/png');
  
  // upload if file is OK
  if (in_array($_FILES['image']['type'], $permitted)
      && $_FILES['image']['size'] > 0 
      && $_FILES['image']['size'] <= MAX_FILE_SIZE) {
    switch($_FILES['image']['error']) {
      case 0:
        // check if a file of the same name has been uploaded
        if (!file_exists(UPLOAD_DIR . $file)) {
          // move the file to the upload folder and rename it
          $success =
move_uploaded_file($_FILES['image']['tmp_name'], UPLOAD_DIR .
$file);
        } else {
          $result = 'A file of the same name already exists.';
        }
        if ($success) {
          $result = "$file uploaded successfully.";
        } else {
          $result = "Error uploading $file. Please try again.";
        }
        break;
      case 3:
      case 6:
      case 7:
      case 8:
        $result = "Error uploading $file. Please try again.";
        break;
      case 4:
        $result = "You didn't select a file to be uploaded.";
    }
  } else {
    $result = "$file is either too big or not an image.";
  }
}
?>

The condition if (array_key_exists('upload', $_POST)) ensures the processing script is run only if the form has been submitted by checking if the $_POST array contains the name of the submit button (in this case, upload).

All that you should need to change in this script are the two constants, MAX_FILE_SIZE and UPLOAD_DIR.

This example sets MAX_FILE_SIZE to 1024 * 50 - in other words, 50KB.

Set the value of UPLOAD_DIR to the images folder that you want the image to be uploaded to. Use a fully qualified path (NOT a URL), and make sure it is followed by a forward slash.

If the file name matches the placeholder name, it will automatically be displayed in a web page that is expecting the image. So, if you upload fido.jpg to the images folder, and you have a page that uses <img src="/images/fido.jpg" />, it will be displayed as soon as the page is accessed after the upload.

This code prevents the same file from being uploaded twice. If you want to replace an existing image, remove the if... else condition around the following line:

$success = move_uploaded_file($_FILES['image']['tmp_name'],
UPLOAD_DIR . $file);

To show the result of the upload, put the following code immediately above the form in the body of the page:

<?php
// if the form has been submitted, display result
if (isset($result)) {
  echo "<p><strong>$result</strong></p>";
}
?>

+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes