What are potential security risks associated with file uploads in PHP?
Potential security risks associated with file uploads in PHP include allowing malicious files to be uploaded, leading to potential security vulnerabilities such as code execution, file inclusion, and denial of service attacks. To mitigate these risks, it is important to validate file types, restrict file sizes, and store uploaded files in a secure directory outside of the web root.
// Check if the file type is allowed
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($_FILES['file']['type'], $allowedTypes)) {
die('Invalid file type. Only JPEG, PNG, and GIF files are allowed.');
}
// Check if the file size is within limit
$maxFileSize = 1048576; // 1MB
if ($_FILES['file']['size'] > $maxFileSize) {
die('File size exceeds the limit of 1MB.');
}
// Store uploaded file in a secure directory
$uploadDir = '/var/www/uploads/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
echo 'File uploaded successfully.';
} else {
echo 'Failed to upload file.';
}