Secure File Uploads in PHP (Images, PDFs, and Safety)
Upload files safely by validating type, size, and storing outside public directories when possible.
File uploads are a common attack target. You must validate everything. ## Step 1: HTML form ```html <form method="post" enctype="multipart/form-data"> <input type="file" name="avatar" /> <button>Upload</button> </form> ``` ## Step 2: Server-side checks Rules: - limit file size - validate mime type using finfo - generate safe filename - store in uploads folder (prefer outside public web root) ```php <?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (!isset($_FILES['avatar']) || $_FILES['avatar']['error'] !== UPLOAD_ERR_OK) { die("Upload failed"); } $file = $_FILES['avatar']; if ($file['size'] > 2 * 1024 * 1024) { die("File too large"); } $finfo = new finfo(FILEINFO_MIME_TYPE); $mime = $finfo->file($file['tmp_name']); $allowed = [ "image/jpeg" => "jpg", "image/png" => "png", ]; if (!isset($allowed[$mime])) { die("Invalid file type"); } $ext = $allowed[$mime]; $safeName = bin2hex(random_bytes(16)) . "." . $ext; $uploadDir = __DIR__ . "/uploads"; if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true); $dest = $uploadDir . "/" . $safeName; if (!move_uploaded_file($file['tmp_name'], $dest)) { die("Could not save file"); } echo "Uploaded successfully"; } ?> ``` ## Big security warning Never trust the original filename, and never allow uploading `.php` into a public folder. > Next: Password reset flow (token-based), like professional apps.