File Upload in PHP
? File Upload in PHP
PHP makes it easy to upload files like images, documents, and more using a simple HTML form and the $_FILES superglobal.
? Step 1: Create the HTML Upload Form
<!-- upload.html --><form action="upload.php" method="post" enctype="multipart/form-data"> Select file to upload: <input type="file" name="myfile"> <input type="submit" value="Upload File"></form>? The
enctype="multipart/form-data"is required for file uploads!
? Step 2: Handle the Upload in PHP
<?php// upload.phpif ($_SERVER['REQUEST_METHOD'] == 'POST') { $target_dir = "uploads/"; // Make sure this folder exists and is writable $target_file = $target_dir . basename($_FILES["myfile"]["name"]); if (move_uploaded_file($_FILES["myfile"]["tmp_name"], $target_file)) { echo "The file " . htmlspecialchars(basename($_FILES["myfile"]["name"])) . " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; }}?>? $_FILES Array Breakdown
$_FILES['myfile']['name'] // Original filename$_FILES['myfile']['type'] // MIME type (e.g., image/jpeg)$_FILES['myfile']['size'] // File size in bytes$_FILES['myfile']['tmp_name'] // Temp file path$_FILES['myfile']['error'] // Error code (0 = OK)? Best Practices
? Check file size
? Validate file type (e.g., only allow images or PDFs)
? Sanitize file names
? Set permissions on upload folder
? Avoid directly using user input for file paths
? Example: Allow Only Images
$allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];$fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));if (!in_array($fileType, $allowedTypes)) { echo "Only JPG, JPEG, PNG & GIF files are allowed."; exit;}? Sample Folder Structure
project/??? upload.html??? upload.php??? uploads/ ? must be writable (e.g. chmod 755 or 777)