How can one ensure secure image upload in PHP?
To ensure secure image upload in PHP, one should validate the file type, check the file size, and store the uploaded images in a secure directory outside of the web root to prevent direct access.
<?php
// Define allowed file types
$allowed_types = array('jpg', 'jpeg', 'png', 'gif');
// Check if the file is an image
if (isset($_FILES['image']) && $_FILES['image']['error'] == UPLOAD_ERR_OK) {
$file_info = pathinfo($_FILES['image']['name']);
$file_ext = strtolower($file_info['extension']);
if (in_array($file_ext, $allowed_types)) {
// Check file size
if ($_FILES['image']['size'] <= 5000000) {
// Move uploaded file to secure directory
move_uploaded_file($_FILES['image']['tmp_name'], '/path/to/secure/directory/' . $_FILES['image']['name']);
echo 'Image uploaded successfully.';
} else {
echo 'File size exceeds limit.';
}
} else {
echo 'Invalid file type.';
}
} else {
echo 'Error uploading file.';
}
?>