What are common pitfalls when using file upload in PHP scripts?
One common pitfall when using file upload in PHP scripts is not properly validating the file type and size before processing the upload. This can lead to security vulnerabilities such as allowing malicious files to be uploaded to the server. To solve this issue, always validate the file type and size before moving the uploaded file to its destination directory.
// Validate file type and size before moving the uploaded file
$allowedTypes = ['image/jpeg', 'image/png'];
$maxSize = 1048576; // 1MB
if (in_array($_FILES['file']['type'], $allowedTypes) && $_FILES['file']['size'] <= $maxSize) {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
echo 'File uploaded successfully.';
} else {
echo 'Invalid file type or size.';
}
Related Questions
- What are the key elements and functions to consider when structuring HTML templates with OOP in PHP?
- What function can be used to convert line breaks in text to HTML line breaks in PHP?
- How does using SUM() in a SQL query differ from manually calculating the total sum in PHP code when working with PDO?