How can PHP be used to securely upload and display images from external hosts?
To securely upload and display images from external hosts using PHP, you can validate the image file type, restrict file size, and store the images in a secure location on your server. When displaying the images, use appropriate headers to prevent direct access to the image files.
<?php
// Check if a file was uploaded
if(isset($_FILES['image'])){
$file = $_FILES['image'];
// Validate file type
$allowedTypes = ['image/jpeg', 'image/png'];
if(!in_array($file['type'], $allowedTypes)){
die('Invalid file type. Only JPEG and PNG files are allowed.');
}
// Restrict file size
if($file['size'] > 5242880){ // 5MB
die('File size is too large. Maximum file size is 5MB.');
}
// Store the image in a secure location
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($file['name']);
if(move_uploaded_file($file['tmp_name'], $uploadFile)){
echo 'Image uploaded successfully.';
} else {
echo 'Failed to upload image.';
}
}
?>