2 min read

PHP File Uploads

With PHP, it is easy to upload files to the server. However, with ease comes danger, so always be careful when allowing file uploads!


1. The HTML Form

To allow users to upload files, the <form> tag must use the method="post" and enctype="multipart/form-data" attributes.

<form action="upload.php" method="post" enctype="multipart/form-data">
  Select image to upload:
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input type="submit" value="Upload Image" name="submit">
</form>

2. The PHP Script

The uploaded file information is stored in the $_FILES superglobal.

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    echo "The file ". htmlspecialchars(basename($_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
}

3. The $_FILES Array

  • $_FILES['file']['name']: The original name of the file on the client machine.
  • $_FILES['file']['type']: The mime type of the file (e.g. "image/gif").
  • $_FILES['file']['size']: The size of the file in bytes.
  • $_FILES['file']['tmp_name']: The temporary filename of the file in which the uploaded file was stored on the server.
  • $_FILES['file']['error']: The error code associated with this file upload.

4. Basic Validation

Always validate uploads to ensure security.

// Check if file already exists
if (file_exists($target_file)) {
  echo "Sorry, file already exists.";
  $uploadOk = 0;
}

// Check file size (e.g. limit to 500KB)
if ($_FILES["fileToUpload"]["size"] > 500000) {
  echo "Sorry, your file is too large.";
  $uploadOk = 0;
}

programming/php/php programming/php/php-forms programming/php/php-security