What best practices should be followed when handling file uploads in PHP to prevent errors and vulnerabilities?
When handling file uploads in PHP, it is crucial to validate and sanitize the file data to prevent errors and vulnerabilities such as file injection attacks. One common best practice is to check the file type and size before allowing it to be uploaded to the server. Additionally, it is recommended to store uploaded files in a secure directory outside the web root to prevent direct access.
// Validate file type and size before uploading
$allowedTypes = ['image/jpeg', 'image/png'];
$maxSize = 1048576; // 1MB
if (in_array($_FILES['file']['type'], $allowedTypes) && $_FILES['file']['size'] <= $maxSize) {
// Move uploaded file to a secure directory
move_uploaded_file($_FILES['file']['tmp_name'], '/path/to/secure/directory/' . $_FILES['file']['name']);
echo 'File uploaded successfully.';
} else {
echo 'Invalid file type or size.';
}