What are the best practices for handling file uploads in PHP to prevent common errors or vulnerabilities?
When handling file uploads in PHP, it is important to validate the file type, size, and ensure secure storage to prevent common errors or vulnerabilities like malicious file uploads or directory traversal attacks. One way to mitigate these risks is by using PHP's built-in functions like `move_uploaded_file()` and `is_uploaded_file()` to securely handle file uploads and store them in a designated directory.
<?php
// Check if the file was uploaded without errors
if ($_FILES['file']['error'] == UPLOAD_ERR_OK) {
// Validate file type
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (in_array($_FILES['file']['type'], $allowedTypes)) {
// Validate file size
if ($_FILES['file']['size'] <= 5000000) {
// Move the uploaded file to 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 'Failed to move file.';
}
} else {
echo 'File is too large.';
}
} else {
echo 'Invalid file type.';
}
} else {
echo 'File upload error.';
}
?>