What are common pitfalls to avoid when uploading and storing images in a PHP application?

One common pitfall to avoid when uploading and storing images in a PHP application is not validating the file type properly. This can lead to security vulnerabilities such as allowing users to upload malicious files. To prevent this, always check the file type before storing the image.

// 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.');
}

// Move the uploaded file to a secure location
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($_FILES['image']['name']);
move_uploaded_file($_FILES['image']['tmp_name'], $uploadFile);

// Store the file path in the database
$imagePath = $uploadFile;
// Insert $imagePath into the database