What potential issues can arise when handling file uploads via HTTP in PHP?
One potential issue when handling file uploads via HTTP in PHP is the risk of allowing malicious files to be uploaded to the server. To mitigate this risk, it is important to validate the file type, size, and content before saving it to the server.
// Check if the file type is allowed
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($_FILES['file']['type'], $allowedTypes)) {
die('Error: Invalid file type.');
}
// Check if the file size is within limits
$maxFileSize = 1048576; // 1MB
if ($_FILES['file']['size'] > $maxFileSize) {
die('Error: File size exceeds limit.');
}
// Check if the file is actually an uploaded file
if (!is_uploaded_file($_FILES['file']['tmp_name'])) {
die('Error: Invalid file.');
}
// Move the uploaded file to the desired 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.';
}