What potential security risks are associated with handling user-uploaded files in PHP?
Handling user-uploaded files in PHP can pose security risks such as allowing malicious files to be uploaded to the server, which could lead to code execution or other attacks. To mitigate this risk, it is important to validate the file type, sanitize the file name, and store the files in a secure directory outside of the web root.
// Validate file type
$allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
$file_extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array($file_extension, $allowed_types)) {
die('Invalid file type.');
}
// Sanitize file name
$clean_filename = preg_replace("/[^A-Za-z0-9.]/", '', $_FILES['file']['name']);
// Store file in secure directory
$upload_dir = '/path/to/secure/directory/';
move_uploaded_file($_FILES['file']['tmp_name'], $upload_dir . $clean_filename);