What are some best practices for handling file uploads in PHP, especially when it comes to security and user input validation?
When handling file uploads in PHP, it is crucial to validate user input to prevent malicious uploads and ensure the security of your application. One best practice is to check the file type and size before allowing the upload. Additionally, always store uploaded files in a secure directory outside of the web root to prevent direct access.
// Validate file type and size before allowing upload
$allowedTypes = ['image/jpeg', 'image/png'];
$maxSize = 1048576; // 1MB
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
$fileType = $_FILES['file']['type'];
$fileSize = $_FILES['file']['size'];
if (in_array($fileType, $allowedTypes) && $fileSize <= $maxSize) {
$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.';
}
} else {
echo 'Invalid file type or size.';
}
} else {
echo 'Error uploading file.';
}