PHP File Upload

To handle file uploads in PHP, you can use the $_FILES superglobal. Here’s a basic example of how to handle file uploads in PHP:

HTML Form (upload_form.html)

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Upload Form</title> </head> <body> <form action="upload.php" method="post" enctype="multipart/form-data"> <label for="file">Select a file to upload:</label> <input type="file" name="file" id="file" required> <br> <input type="submit" value="Upload File" name="submit"> </form> </body> </html>

PHP File (upload.php)

<?php // Check if the form is submitted if (isset($_POST['submit'])) { // Check if the file is uploaded if (isset($_FILES['file']) && $_FILES['file']['error'] == 0) { $fileName = $_FILES['file']['name']; $fileTmpName = $_FILES['file']['tmp_name']; $fileSize = $_FILES['file']['size']; $fileError = $_FILES['file']['error']; $fileType = $_FILES['file']['type']; // Define allowed file types (example: images) $allowed = ['jpg', 'jpeg', 'png', 'gif']; $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION)); // Check file extension if (in_array($fileExt, $allowed)) { // Check file size (max 5MB for example) if ($fileSize <= 5000000) { // Define the upload path $uploadDir = 'uploads/'; if (!is_dir($uploadDir)) { mkdir($uploadDir, 0777, true); } $fileDestination = $uploadDir . basename($fileName); // Move the uploaded file to the desired location if (move_uploaded_file($fileTmpName, $fileDestination)) { echo "File successfully uploaded!"; } else { echo "Error uploading the file!"; } } else { echo "File is too large! Max size is 5MB."; } } else { echo "Invalid file type. Only JPG, JPEG, PNG, and GIF are allowed."; } } else { echo "No file uploaded or error occurred during upload."; } } ?>

Explanation:

  1. HTML Form: The form uses enctype="multipart/form-data" to ensure that file data can be sent.

  2. PHP Script:

    • Checks if the form is submitted and the file is uploaded correctly.

    • Validates the file type and size.

    • Moves the uploaded file to a directory (uploads/).

    • Provides feedback to the user (success or error).

Notes:

  • File Validation: Ensure proper validation to avoid uploading unwanted files.

  • Security: Always sanitize and validate file types and sizes to prevent security issues such as file injection attacks.

  • Permissions: Ensure the directory has proper write permissions.