Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

File Uploads with PHP

Introduction

Uploading files is a common use case in web applications. It allows users to upload files from their local system to the server. In this tutorial, we'll cover how to handle file uploads in PHP from start to finish.

Creating the HTML Form

To upload files, you'll need to create an HTML form that uses the multipart/form-data enctype. This tells the browser to encode the file's contents as part of the form submission. Here's an example of a basic file upload form:

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

Handling the File Upload in PHP

When the form is submitted, the file is sent to the server and can be accessed via the $_FILES superglobal. Here's a simple PHP script to handle the file upload:

<?php
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

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

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

    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
        && $imageFileType != "gif" ) {
      echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
      $uploadOk = 0;
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
      echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
      if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
      } else {
        echo "Sorry, there was an error uploading your file.";
      }
    }
  }
?>

Security Considerations

Handling file uploads safely is crucial to prevent security vulnerabilities. Here are some tips:

  • Ensure the file is of an acceptable type by checking its MIME type and file extension.
  • Limit the file size to prevent denial of service attacks.
  • Store the files in a directory outside the web root to prevent direct access.
  • Rename the uploaded files to prevent overwriting existing files and to obscure the original file names.

Example: Complete File Upload Script

Below is a complete example that includes the HTML form and the PHP script:

<!-- HTML Form -->
<form action="upload.php" method="post" enctype="multipart/form-data">
  <label for="fileToUpload">Select file to upload:</label>
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input type="submit" value="Upload File" name="submit">
</form>

<!-- PHP Script (upload.php) -->
<?php
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

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

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

    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
        && $imageFileType != "gif" ) {
      echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
      $uploadOk = 0;
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
      echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
      if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
      } else {
        echo "Sorry, there was an error uploading your file.";
      }
    }
  }
?>

Conclusion

Handling file uploads in PHP is straightforward but requires careful attention to security details. By following the steps outlined in this tutorial, you can safely allow users to upload files to your server.