What security measures should be taken when allowing file uploads on a PHP server?
When allowing file uploads on a PHP server, it is important to implement security measures to prevent malicious files from being uploaded. One common approach is to restrict the file types that can be uploaded, validate file size, and store the uploaded files outside of the web root directory to prevent direct access.
// Set allowed file types
$allowed_types = array('jpg', 'jpeg', 'png', 'gif');
// Set maximum file size
$max_size = 2 * 1024 * 1024; // 2MB
// Set upload directory outside of web root
$upload_dir = '/var/www/uploads/';
// Check if file type is allowed
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array($ext, $allowed_types)) {
die('Invalid file type.');
}
// Check file size
if ($_FILES['file']['size'] > $max_size) {
die('File is too large.');
}
// Move uploaded file to upload directory
if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_dir . $_FILES['file']['name'])) {
echo 'File uploaded successfully.';
} else {
echo 'Error uploading file.';
}