What are potential pitfalls to be aware of when sending images via a contact form in PHP?
When sending images via a contact form in PHP, potential pitfalls to be aware of include file size limitations, file type restrictions, and security vulnerabilities such as allowing malicious files to be uploaded. To solve these issues, you can validate the file size and type before processing the upload, and ensure that the uploaded files are stored in a secure directory outside of the web root.
// Check file size and type before processing upload
if ($_FILES['image']['size'] > 5000000) {
echo "File is too large. Please upload a smaller file.";
exit;
}
$allowed_types = array('image/jpeg', 'image/png', 'image/gif');
if (!in_array($_FILES['image']['type'], $allowed_types)) {
echo "Invalid file type. Please upload a JPEG, PNG, or GIF file.";
exit;
}
// Store uploaded files in a secure directory outside of the web root
$upload_dir = '/path/to/secure/directory/';
$upload_file = $upload_dir . basename($_FILES['image']['name']);
if (move_uploaded_file($_FILES['image']['tmp_name'], $upload_file)) {
echo "File uploaded successfully.";
} else {
echo "Error uploading file.";
}