What security measures should be implemented when handling file uploads in PHP?
When handling file uploads in PHP, it is important to implement security measures to prevent malicious files from being uploaded to your server. One way to do this is by checking the file type and size before allowing the upload to proceed. Additionally, you can rename the file to a random string to prevent any potential security risks associated with using the original file name.
// Check file type and size
$allowedTypes = ['image/jpeg', 'image/png'];
$maxSize = 5242880; // 5MB
if (!in_array($_FILES['file']['type'], $allowedTypes) || $_FILES['file']['size'] > $maxSize) {
die('Invalid file type or size.');
}
// Rename file to a random string
$fileName = uniqid() . '_' . $_FILES['file']['name'];
$uploadPath = '/path/to/uploads/' . $fileName;
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath)) {
echo 'File uploaded successfully.';
} else {
echo 'Error uploading file.';
}