What are some common pitfalls when using PHP for sending emails and uploading files?
One common pitfall when sending emails in PHP is not properly sanitizing user input, which can lead to security vulnerabilities such as injection attacks. To solve this, always validate and sanitize user input before using it in email headers or content.
// Sanitize user input for email headers
$subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
$to = filter_var($_POST['to'], FILTER_SANITIZE_EMAIL);
$headers = "From: " . filter_var($_POST['from'], FILTER_SANITIZE_EMAIL);
// Send email
mail($to, $subject, $message, $headers);
```
Another common pitfall when uploading files in PHP is not restricting the file types or sizes that can be uploaded, which can lead to security risks and server overload. To solve this, always validate the file type and size before allowing the upload to proceed.
```php
// Validate file type and size
$allowedTypes = ['image/jpeg', 'image/png'];
$maxSize = 5 * 1024 * 1024; // 5MB
if (in_array($_FILES['file']['type'], $allowedTypes) && $_FILES['file']['size'] <= $maxSize) {
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
} else {
echo "Invalid file type or size.";
}