What are best practices for handling file uploads and processing in PHP applications?
When handling file uploads in PHP applications, it is important to validate the file type, size, and ensure secure storage and processing to prevent security vulnerabilities. One best practice is to use PHP's built-in functions like `move_uploaded_file()` to move the uploaded file to a secure directory on the server.
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
$file_name = $_FILES['file']['name'];
$file_tmp = $_FILES['file']['tmp_name'];
// Validate file type and size
$allowed_types = ['image/jpeg', 'image/png'];
$max_size = 5 * 1024 * 1024; // 5MB
if (in_array($_FILES['file']['type'], $allowed_types) && $_FILES['file']['size'] <= $max_size) {
$upload_dir = 'uploads/';
if (!file_exists($upload_dir)) {
mkdir($upload_dir, 0777, true);
}
// Move uploaded file to secure directory
if (move_uploaded_file($file_tmp, $upload_dir . $file_name)) {
echo 'File uploaded successfully.';
} else {
echo 'Error uploading file.';
}
} else {
echo 'Invalid file type or size.';
}
} else {
echo 'Error uploading file.';
}