PHP / PHP Forms and User Input

Working with File Uploads in PHP

This tutorial will introduce you to handling file uploads in PHP. We'll explore how to validate, sanitize, and securely store uploaded files.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Covers handling forms, sanitizing, and validating user input.

Working with File Uploads in PHP

1. Introduction

In this tutorial, we'll be exploring how to handle file uploads in PHP. We'll cover every step from setting up an HTML form to the actual uploading process in PHP, including validation, sanitization, and secure storage of files.

You will learn:

  • How to create a file upload form in HTML
  • How to handle file uploads in PHP
  • How to validate and sanitize uploaded files
  • How to securely store uploaded files

Prerequisites: Basic knowledge of HTML and PHP is recommended.

2. Step-by-Step Guide

2.1 HTML File Upload Form

The first step in uploading files is to create an HTML form that allows users to choose the file they want to upload.

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

Here, "enctype" is set as "multipart/form-data" which is necessary when you're using forms that have a file upload control.

2.2 Handling File Upload in PHP

In PHP, you can access uploaded file information through the global array $_FILES.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $fileToUpload = $_FILES["fileToUpload"];
}
?>

$_FILES["fileToUpload"] is an array of things the client is trying to upload, which includes the following properties: name, type, tmp_name, error, and size.

2.3 Validate and Sanitize File Upload

It's crucial to validate and sanitize the uploaded file for security reasons. We'll check for the file size, type, and ensure it has no errors.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $fileToUpload = $_FILES["fileToUpload"];

    // Check if file has no errors
    if ($fileToUpload["error"] !== 0) {
        die("Sorry, there was an error uploading your file.");
    }

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

    // Allow certain file formats
    $fileType = strtolower(pathinfo($fileToUpload["name"], PATHINFO_EXTENSION));
    if($fileType != "jpg" && $fileType != "png" && $fileType != "jpeg") {
        die("Sorry, only JPG, JPEG, & PNG files are allowed.");
    }
}
?>

2.4 Securely Store Uploaded Files

Finally, we'll move the uploaded file from temporary directory to the desired location.

<?php
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
    echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
}
?>

3. Code Examples

The complete code for handling file uploads in PHP would look like this:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $fileToUpload = $_FILES["fileToUpload"];

    // Check if file has no errors
    if ($fileToUpload["error"] !== 0) {
        die("Sorry, there was an error uploading your file.");
    }

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

    // Allow certain file formats
    $fileType = strtolower(pathinfo($fileToUpload["name"], PATHINFO_EXTENSION));
    if($fileType != "jpg" && $fileType != "png" && $fileType != "jpeg") {
        die("Sorry, only JPG, JPEG, & PNG files are allowed.");
    }

    $targetDir = "uploads/";
    $targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]);
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

4. Summary

In this tutorial, we covered the process of handling file uploads in PHP. We started by creating a file upload form in HTML, then moved on to handling, validating, sanitizing, and securely storing the uploaded files in PHP.

Next steps for learning could include exploring more advanced file and image manipulation techniques, or learning about how to handle multiple file uploads simultaneously.

For your reference, the official PHP documentation on handling file uploads is a great resource: PHP File Uploads

5. Practice Exercises

  1. Exercise: Modify the PHP script to limit the upload file size to 1MB.
  2. Exercise: Expand the file type validation to allow .gif and .pdf files.
  3. Exercise: Implement a feature that renames the uploaded file with a unique name to avoid overwriting existing files.

Solutions:

  1. To limit the file size to 1MB (approx. 1048576 bytes), modify the file size check in the PHP script as follows:
if ($fileToUpload["size"] > 1048576)
  1. To allow .gif and .pdf files, add these conditions to the file type validation:
if($fileType != "jpg" && $fileType != "png" && $fileType != "jpeg" && $fileType != "gif" && $fileType != "pdf")
  1. To rename the uploaded file with a unique name, you can append a timestamp to the original filename:
$targetFile = $targetDir . time() . "_" . basename($_FILES["fileToUpload"]["name"]);

Remember, practice is key in mastering any programming language. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Word to PDF Converter

Easily convert Word documents to PDFs.

Use tool

Color Palette Generator

Generate color palettes from images.

Use tool

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help