fileupload

PHP File Uploads

PHP File Uploads

PHP allows users to upload files through a web form. You can process the uploaded files and store them on the server.

Creating a File Upload Form

To upload a file, you need to create a form with enctype="multipart/form-data":

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

Processing the Uploaded File

In the PHP script, use the $_FILES superglobal to handle the file upload:

      
        <?php
          if ($_SERVER["REQUEST_METHOD"] == "POST") {
            $target_dir = "uploads/";
            $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

            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.";
            }
          }
        ?>
      
    

Activity

Try It Yourself!

Modify the script to check the file type and only allow certain file types (e.g., images or PDFs).

Quiz

Quick Quiz

  1. What attribute must be added to the form tag to enable file uploads?
  2. How can you access the uploaded file data in PHP?

Answers: Use enctype="multipart/form-data" for file uploads. Access uploaded file data using the $_FILES superglobal.