File Uploads

Handling File Uploads

PHP enables you to handle file uploads, which can be useful for allowing users to upload images, documents, or other types of files.

To create an upload form, you need to use the HTML form tag with the enctype attribute set to multipart/form-data. This allows the form to handle binary data, which is necessary for file uploads:

<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>

The PHP script that handles the upload might look something like this:

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;

// Check if image file is an actual image or fake image
if(isset($_POST["submit"])) {
  $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
  if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
  } else {
    echo "File is not an image.";
    $uploadOk = 0;
  }
}

// Attempt to move the uploaded file to the server
if ($uploadOk == 1) {
  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.";
  }
}
?>

This script checks if the uploaded file is an image, and if it is, attempts to move the uploaded file to a directory on the server.

File uploads can open your site to potential security vulnerabilities, so always take precautions when allowing file uploads. Ensure you verify the file type and size, and consider restricting the types of files that can be uploaded.

Last updated