PHP File Upload

PHP File Upload

Allowing users to upload files (like profile pictures, PDFs, or documents) is a highly requested feature in web development. With PHP, handling file uploads is straightforward, provided you follow proper security protocols.


1. Configure The php.ini File

First, ensure that PHP is configured to allow file uploads. In your server's php.ini file, search for the file_uploads directive, and set it to On:

file_uploads = On

2. Create The HTML Form

To allow file uploads, your HTML form must have the enctype="multipart/form-data" attribute. This specifies how the form data should be encoded when submitting it to the server. Without this, the file upload will completely fail!

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

3. The Upload Script (upload.php)

When the form is submitted, the file is sent to the server and stored in a temporary location. You must use the $_FILES superglobal to access the file, and the move_uploaded_file() function to move it to a permanent directory.

Here is a basic example of an upload script:

Upload Script Example

<?php
$target_dir = "uploads/"; // Folder where you want to save the file
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

// Check if file was uploaded without errors if (isset($_FILES["fileToUpload"]) && $_FILES["fileToUpload"]["error"] == 0) {

// Attempt to move the uploaded file to its new destination if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file " . htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has been uploaded."; } else { echo "Sorry, there was an error moving your uploaded file."; }

} else { echo "No file uploaded or an error occurred."; } ?>

Security Warning

The script above is very basic. In a real-world scenario, you must add security checks to verify the file type (e.g., ensuring it's actually an image and not a malicious .php script disguised as an upload), check the file size limits, and verify if the file already exists before moving it.


Exercise

?

Which HTML attribute MUST be included in the form tag to allow file uploads?