w1coding.comAll tutorials

PHP Fileupload

PHP lessons
  1. Environment Setup
  2. Introduction
  3. Variables
  4. Basics
  5. Operators
  6. Control
  7. Loops
  8. Variables
  9. Functions
  10. Arrays
  11. Superglobal
  12. File
  13. Loops
  14. Date
  15. Loops
  16. Strings
  17. Error
  18. Class
  19. File
  20. Include
  21. Sessions
  22. Mysql
  23. Cookies
  24. Forms
  25. Cookies
  26. Regular
  27. Authenthication
  28. Fileupload
  29. Mvc
  30. Responsive

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.