What are some best practices for handling file uploads and displaying their content in PHP?
When handling file uploads in PHP, it is essential to validate the file type and size to prevent security risks. To display the content of uploaded files, you can use appropriate functions based on the file type (e.g., readfile() for text files, imagecreatefromjpeg() for JPEG images). Ensure that you handle errors gracefully and sanitize user input to prevent vulnerabilities.
<?php
// Handle file upload
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
$fileType = $_FILES['file']['type'];
$fileSize = $_FILES['file']['size'];
// Validate file type and size
if (($fileType === 'image/jpeg' || $fileType === 'text/plain') && $fileSize < 1048576) {
$uploadedFilePath = 'uploads/' . $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $uploadedFilePath);
// Display file content
if ($fileType === 'image/jpeg') {
header('Content-Type: image/jpeg');
readfile($uploadedFilePath);
} else if ($fileType === 'text/plain') {
$fileContent = file_get_contents($uploadedFilePath);
echo nl2br($fileContent); // Display text content with line breaks
}
} else {
echo 'Invalid file type or size. Please upload a JPEG image or a text file (max 1MB).';
}
} else {
echo 'Error uploading file. Please try again.';
}
?>
Related Questions
- What potential issue could arise from using $_GET['var'] to retrieve a value in PHP?
- What are the best practices for securely handling user authentication and password storage in PHP applications to prevent unauthorized access to sensitive information?
- Are there any best practices for upgrading PHP versions to avoid breaking changes in libraries like Zend Search?