What security measures should be implemented when using this upload script?
When using an upload script, it is crucial to implement security measures to prevent malicious file uploads. One important measure is to restrict the file types that can be uploaded to only allow safe file formats such as images or documents. Additionally, validate file size limits to prevent large files from being uploaded and potentially causing server issues. Lastly, consider implementing file renaming to avoid overwriting existing files and to prevent attackers from executing malicious scripts by uploading files with executable extensions.
// Restricting file types to only allow images and documents
$allowed_file_types = array('image/jpeg', 'image/png', 'application/pdf');
if (!in_array($_FILES['file']['type'], $allowed_file_types)) {
die('Invalid file type. Only JPEG, PNG, and PDF files are allowed.');
}
// Validating file size limit
$max_file_size = 5 * 1024 * 1024; // 5 MB
if ($_FILES['file']['size'] > $max_file_size) {
die('File size exceeds the limit of 5MB.');
}
// Renaming uploaded file to prevent overwriting and malicious script execution
$upload_dir = 'uploads/';
$upload_file = $upload_dir . uniqid() . '_' . $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $upload_file);
echo 'File uploaded successfully.';