How can file uploads be securely handled in PHP to prevent vulnerabilities?
To securely handle file uploads in PHP and prevent vulnerabilities such as malicious file uploads or directory traversal attacks, it is important to validate the file type, restrict file size, and store the files in a secure directory outside of the web root. Additionally, using functions like move_uploaded_file() and setting appropriate file permissions can help enhance security.
// Example code snippet for handling file uploads securely in PHP
// Define allowed file types
$allowed_types = array('jpg', 'jpeg', 'png', 'gif');
// Validate file type
$file_extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array($file_extension, $allowed_types)) {
die('Invalid file type. Only JPG, JPEG, PNG, and GIF files are allowed.');
}
// Restrict file size
$max_file_size = 1048576; // 1MB
if ($_FILES['file']['size'] > $max_file_size) {
die('File size exceeds the limit of 1MB.');
}
// Move uploaded file to secure directory
$upload_dir = 'uploads/';
$upload_file = $upload_dir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_file)) {
echo 'File uploaded successfully.';
} else {
echo 'File upload failed.';
}