What best practices should be followed when handling file uploads in PHP, especially when dealing with form submissions?
When handling file uploads in PHP, it is important to validate the file type and size to prevent malicious uploads and server overload. Additionally, always store uploaded files outside of the web root directory to prevent direct access. Finally, sanitize file names to avoid any potential security vulnerabilities.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
$file = $_FILES['file'];
// Validate file type
$allowedTypes = ['image/jpeg', 'image/png'];
if (!in_array($file['type'], $allowedTypes)) {
die('Invalid file type.');
}
// Validate file size
$maxFileSize = 1048576; // 1MB
if ($file['size'] > $maxFileSize) {
die('File is too large.');
}
// Store uploaded file outside of web root
$uploadPath = '/var/www/uploads/' . basename($file['name']);
move_uploaded_file($file['tmp_name'], $uploadPath);
// Sanitize file name
$safeFileName = preg_replace("/[^A-Za-z0-9.]/", '', $file['name']);
}
?>
Keywords
Related Questions
- How can the use of inner loops or foreach statements enhance the process of accessing and displaying data stored in arrays in PHP, particularly when dealing with multiple rows and columns of data?
- What are some common pitfalls for beginners when working with arrays in PHP, and how can they be avoided?
- How can developers ensure that optional parameter routing is used effectively and efficiently in PHP projects?