PHP - File Uploading

Hello there, aspiring PHP developers! Today, we're going to dive into the exciting world of file uploading using PHP. As your friendly neighborhood computer teacher, I'm here to guide you through this journey step by step. So, grab your favorite beverage, get comfortable, and let's embark on this file uploading adventure together!

PHP - File Uploading

Understanding File Uploading

Before we jump into the code, let's take a moment to understand what file uploading is all about. Imagine you're sending a letter to a friend. You write the letter, put it in an envelope, and send it through the postal service. File uploading is quite similar! Instead of a letter, you're sending a file (like an image or a document) from your computer to a web server.

Creating a File Upload Form

The first step in our file uploading journey is to create an HTML form that allows users to select and upload a file. Think of this form as the envelope we use to send our letter.

Let's create a simple HTML form:

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

Let's break this down:

  1. action="upload.php": This tells the form where to send the data. In this case, we'll create a PHP script called upload.php to handle the file upload.
  2. method="post": This specifies that we're using the POST method to send data.
  3. enctype="multipart/form-data": This is crucial! It tells the form that we're sending more than just text – we're sending a file.
  4. <input type="file">: This creates a button that allows users to select a file from their computer.

Creating an Upload Script

Now that we have our form, we need to create the PHP script that will handle the file upload. This is where the magic happens!

Let's create our upload.php file:

<?php
if(isset($_POST["submit"])) {
    $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.";
        }
    }
}
?>

Wow, that's a lot of code! Don't worry, we'll break it down step by step:

  1. First, we check if the form has been submitted using isset($_POST["submit"]).

  2. We set up some variables:

    • $target_dir: The directory where we'll store uploaded files.
    • $target_file: The full path of the uploaded file.
    • $uploadOk: A flag to track if it's okay to upload the file.
    • $imageFileType: The file extension of the uploaded file.
  3. We perform some checks:

    • Is the file already in our uploads folder?
    • Is the file too large?
    • Is the file type allowed?
  4. If any of these checks fail, we set $uploadOk to 0.

  5. Finally, if everything is okay ($uploadOk == 1), we use the move_uploaded_file() function to move the uploaded file from its temporary location to our uploads folder.

Common File Upload Methods

Here's a table of common methods used in PHP file uploading:

Method Description
$_FILES["file"]["name"] The original name of the file on the client machine
$_FILES["file"]["type"] The MIME type of the file
$_FILES["file"]["size"] The size of the file in bytes
$_FILES["file"]["tmp_name"] The temporary filename of the file stored on the server
$_FILES["file"]["error"] The error code associated with this file upload
move_uploaded_file() Moves an uploaded file to a new location

Conclusion

And there you have it, folks! We've created a form that allows users to select a file, and a PHP script that handles the upload process, complete with error checking and file type restrictions.

Remember, file uploading can be a security risk if not handled properly. Always validate and sanitize user inputs, restrict file types and sizes, and store uploaded files in a directory that's not accessible directly through a web browser.

As we wrap up this lesson, I'm reminded of a student who once uploaded a 1GB video file to a website meant for profile pictures. Needless to say, it didn't end well for the server! So always remember to set those file size limits, folks!

Keep practicing, keep coding, and most importantly, keep having fun with PHP! Until next time, happy uploading!

Credits: Image by storyset