What are the common pitfalls when handling file uploads and database operations in PHP?
One common pitfall when handling file uploads in PHP is not validating the file type and size before saving it to the server, which can lead to security vulnerabilities. To solve this, always validate the file type and size before processing the upload.
// Validate file type and size before saving to the server
if ($_FILES['file']['type'] == 'image/jpeg' && $_FILES['file']['size'] < 5000000) {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
echo 'File uploaded successfully!';
} else {
echo 'Invalid file type or size. Please upload a JPEG image less than 5MB.';
}
Related Questions
- What are the potential pitfalls of using the "like tab1.id=tab2.id" approach to join tables in PHP?
- How can one configure a mail server in PHP to avoid authentication issues when sending emails?
- How can PHP developers prevent cross-site request forgery (CSRF) attacks when processing form data from external sources?