What are the best practices for handling file uploads in PHP, including directory creation and file moving?
When handling file uploads in PHP, it is important to ensure proper security measures are in place to prevent malicious uploads. This includes validating file types, setting file size limits, and sanitizing file names. Additionally, creating a unique directory for each upload and moving the files to that directory can help organize and secure the uploaded files.
<?php
// Validate file type
$allowed_types = array('image/jpeg', 'image/png', 'image/gif');
if (!in_array($_FILES['file']['type'], $allowed_types)) {
die('Invalid file type.');
}
// Set file size limit
$max_size = 5 * 1024 * 1024; // 5MB
if ($_FILES['file']['size'] > $max_size) {
die('File size exceeds limit.');
}
// Sanitize file name
$filename = preg_replace("/[^A-Za-z0-9.]/", '', $_FILES['file']['name']);
// Create unique directory
$upload_dir = 'uploads/' . uniqid() . '/';
if (!file_exists($upload_dir)) {
mkdir($upload_dir, 0777, true);
}
// Move file to directory
if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_dir . $filename)) {
echo 'File uploaded successfully.';
} else {
echo 'Failed to upload file.';
}
?>