All Tutorials

Your One-Stop Destination for Learning and Growth

Uploading Files with PHP: A Simple Guide

When it comes to creating dynamic web applications, handling user-uploaded files is a common requirement. In this blog post, we'll explore how to upload files using PHP. The process we'll cover is quite straightforward and doesn't require any specific libraries or frameworks. Let's get started!

Prerequisites

Before diving into the code, make sure you have the following:

  1. A text editor (e.g., Visual Studio Code, Sublime Text)
  2. A web server with PHP installed
  3. Basic understanding of HTML and PHP

The HTML Form

First, let's create a simple HTML form for users to upload files. Save the following code as index.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload</title>
</head>
<body>
    <h1>Upload File</h1>
    <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>
</body>
</html>

Here, we have an HTML form with a file input field and a submit button. The enctype="multipart/form-data" attribute is essential for handling file uploads.

The PHP Script

Now let's write the PHP script that will handle the file upload. Create a new file named upload.php:

<?php
// Ensure form was submitted
if (isset($_FILES['fileToUpload'])) {
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    // Check if file already exists
    if (file_exists($target_file)) {
        echo "The file already exists.";
    } else {
        move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    }
}
?>

This script checks if the form was submitted, retrieves the uploaded file information and stores it in the uploads directory. If the file already exists, an error message is displayed; otherwise, the file is moved to the target directory.

Testing Your Setup

Now that you have both files, place them in the same directory on your web server and run the index.php file through your browser. Users should be able to upload files using the form.

That's it! This is a simple guide for handling user-uploaded files with PHP. For more advanced use cases (e.g., limiting file size, checking file types), you might want to explore libraries like UploadHandler or frameworks such as Laravel or Symfony. Happy coding!

Published February, 2016