What are the potential consequences of not properly handling file uploads in PHP?
Improperly handling file uploads in PHP can lead to security vulnerabilities such as allowing malicious files to be uploaded to the server, potentially leading to code execution or data breaches. To properly handle file uploads in PHP, ensure that file types are restricted, file sizes are limited, and that uploaded files are stored in a secure location on the server.
<?php
// Check if the file was uploaded without errors
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
// Limit file types and sizes
$allowedTypes = ['image/jpeg', 'image/png'];
$maxFileSize = 1000000; // 1MB
if (in_array($_FILES['file']['type'], $allowedTypes) && $_FILES['file']['size'] <= $maxFileSize) {
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
echo "File uploaded successfully.";
} else {
echo "Failed to upload file.";
}
} else {
echo "Invalid file type or size.";
}
} else {
echo "Error uploading file.";
}
?>