What are common pitfalls to avoid when using an upload script in PHP?
One common pitfall to avoid when using an upload script in PHP is not validating the file type before allowing it to be uploaded. This can lead to security vulnerabilities such as allowing malicious files to be uploaded to your server. To solve this issue, always check the file type using the `$_FILES` superglobal before moving the file to its final destination.
// Check file type before uploading
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($_FILES['file']['type'], $allowedTypes)) {
die('Invalid file type. Only JPEG, PNG, and GIF files are allowed.');
}
// Move uploaded file to final destination
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);