What are the limitations and security considerations when handling file uploads from clients to servers in PHP?
When handling file uploads from clients to servers in PHP, it is important to consider limitations such as file size, file type, and potential security vulnerabilities like malicious file uploads. To mitigate these risks, always validate file types, limit file size, and store uploaded files in a secure directory outside of the web root.
// Check file type
$allowedTypes = ['image/jpeg', 'image/png'];
if (!in_array($_FILES['file']['type'], $allowedTypes)) {
die('Invalid file type.');
}
// Limit file size
$maxFileSize = 5000000; // 5MB
if ($_FILES['file']['size'] > $maxFileSize) {
die('File size is too large.');
}
// Store uploaded file in a secure directory
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
echo 'File uploaded successfully.';
} else {
echo 'File upload failed.';
}