What potential pitfalls should be considered when implementing a script to handle file uploads in PHP?
One potential pitfall when implementing a script to handle file uploads in PHP is the risk of allowing malicious files to be uploaded to the server. To mitigate this risk, it is important to validate the file type and size before allowing the upload to proceed. Additionally, it is crucial to store uploaded files in a secure directory outside of the web root to prevent direct access to them.
// Validate file type and size
$allowedTypes = ['image/jpeg', 'image/png'];
$maxFileSize = 1048576; // 1MB
if (!in_array($_FILES['file']['type'], $allowedTypes) || $_FILES['file']['size'] > $maxFileSize) {
die('Invalid file. Please upload a JPEG or PNG file under 1MB.');
}
// Store uploaded file in a secure directory
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
echo 'File uploaded successfully.';
} else {
echo 'Error uploading file.';
}