What are some common mistakes to avoid when working with file uploads and displaying images in PHP?
One common mistake when working with file uploads in PHP is not validating the file type before allowing it to be uploaded. To avoid security risks, always check the file type and only allow specific file types to be uploaded. Additionally, another common mistake is not properly sanitizing the file name before saving it to the server to prevent against directory traversal attacks.
// Validate file type before allowing upload
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($_FILES['file']['type'], $allowedTypes)) {
die('Invalid file type. Allowed types: jpeg, png, gif');
}
// Sanitize file name before saving to server
$fileName = preg_replace("/[^A-Za-z0-9.]/", '', $_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $fileName);