What are the security risks associated with the code provided for uploading and retrieving images in PHP?
The code provided for uploading and retrieving images in PHP is vulnerable to security risks such as file upload vulnerabilities, directory traversal attacks, and potential injection attacks. To mitigate these risks, it is important to validate and sanitize user input, restrict file types, and store uploaded files in a secure directory outside of the web root.
// Secure image upload and retrieval in PHP
// Validate file type and size before uploading
$allowed_types = ['image/jpeg', 'image/png'];
$max_size = 5 * 1024 * 1024; // 5MB
if (in_array($_FILES['image']['type'], $allowed_types) && $_FILES['image']['size'] <= $max_size) {
$upload_dir = 'uploads/';
$upload_file = $upload_dir . basename($_FILES['image']['name']);
// Move uploaded file to secure directory
if (move_uploaded_file($_FILES['image']['tmp_name'], $upload_file)) {
echo 'File uploaded successfully.';
} else {
echo 'Error uploading file.';
}
} else {
echo 'Invalid file type or size.';
}
// Retrieve and display uploaded images
$files = glob('uploads/*.{jpg,jpeg,png}', GLOB_BRACE);
foreach ($files as $file) {
echo '<img src="' . $file . '" alt="Uploaded Image">';
}