What best practices should be followed when incorporating file uploads in PHP scripts for contact forms?
When incorporating file uploads in PHP scripts for contact forms, it is important to validate the file type and size to prevent malicious uploads and potential security risks. Additionally, ensure that the file is stored in a secure directory and assign a unique filename to avoid overwriting existing files.
<?php
// Check if a file was uploaded
if(isset($_FILES['file'])){
$file = $_FILES['file'];
// Validate file type
$allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
if(!in_array($file['type'], $allowedTypes)){
echo "Invalid file type. Allowed types: JPEG, PNG, PDF";
}
// Validate file size
$maxSize = 5242880; // 5MB
if($file['size'] > $maxSize){
echo "File is too large. Maximum size is 5MB";
}
// Move file to secure directory with unique filename
$uploadDir = 'uploads/';
$fileName = uniqid() . '_' . $file['name'];
move_uploaded_file($file['tmp_name'], $uploadDir . $fileName);
echo "File uploaded successfully!";
}
?>
Related Questions
- In what scenarios would it be preferable to store data in a database instead of a TXT file when working with PHP?
- What are some best practices for handling form submissions in PHP to ensure data integrity and prevent duplicates?
- Are there any common pitfalls or challenges when developing a PHP forum from scratch, especially in terms of integrating HTML elements within PHP code?