What are the recommended security measures for handling user-uploaded images in a PHP application?
When handling user-uploaded images in a PHP application, it is important to implement security measures to prevent malicious files from being uploaded and executed on the server. One recommended approach is to validate the file type and size before allowing the upload. Additionally, it is advisable to store the images outside of the web root directory to prevent direct access.
// Check if the uploaded file is an image
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($_FILES['image']['type'], $allowedTypes)) {
die('Invalid file type. Only JPEG, PNG, and GIF files are allowed.');
}
// Check the file size
$maxSize = 5 * 1024 * 1024; // 5MB
if ($_FILES['image']['size'] > $maxSize) {
die('File is too large. Maximum file size allowed is 5MB.');
}
// Move the uploaded file to a secure directory
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($_FILES['image']['name']);
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadFile)) {
echo 'File uploaded successfully.';
} else {
echo 'Failed to upload file.';
}