What are some potential security risks associated with PHP file uploads and how can they be mitigated?
One potential security risk associated with PHP file uploads is the possibility of allowing malicious files to be uploaded to the server, which can then be executed to compromise the system. To mitigate this risk, it is important to validate the file type and size before allowing the upload to proceed.
// 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 limits
$maxSize = 1048576; // 1MB
if ($_FILES['file']['size'] > $maxSize) {
die('File size exceeds the limit of 1MB.');
}
// Move the uploaded file to a secure location
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
echo 'File uploaded successfully.';
} else {
echo 'Error uploading file.';
}