What are some common pitfalls when uploading images in PHP scripts?
One common pitfall when uploading images in PHP scripts is not validating the file type before processing the upload. This can lead to security vulnerabilities if malicious files are uploaded. To solve this issue, always check the file type of the uploaded image before moving it to the designated directory.
// 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. Please upload a JPEG, PNG, or GIF image.');
}
// Move the uploaded image to the designated directory
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($_FILES['image']['name']);
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadFile)) {
echo 'Image uploaded successfully.';
} else {
echo 'Failed to upload image.';
}