Complete Secure Image Upload Script
Ensuring secure image uploads is crucial for protecting your server and data. This script outlines a comprehensive approach to achieve maximum image upload security.
HTML Form:
<form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="image"> <input type="submit" name="upload" value="Upload"> </form>
PHP:
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif']; if (!in_array($_FILES['image']['type'], $allowedTypes)) { echo "Invalid file type"; exit; }
$verifyimg = getimagesize($_FILES['image']['tmp_name']); if ($verifyimg['mime'] != $_FILES['image']['type']) { echo "Invalid image content"; exit; }
Store uploaded images outside the accessible document root or in a protected directory:
/uploads
Rename and change the extension of uploaded images, and store the original information in a database:
PHP:
$uploadfile = tempnam_sfx($uploaddir, ".tmp"); if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) { // Database logic to store original name and MIME type }
PHP:
$id = 1; // For example $sql = "SELECT name, original_name, mime_type FROM uploads WHERE>
Maximum File Size Validation:
if ($_FILES['image']['size'] > 1000000) { echo "File size too large"; exit; }
ImageUpload Class:
I have created an ImageUpload class to simplify the upload process. Download the package and follow the README for instructions.
Open Source Availability:
The ImageUpload class is now available on GitHub for community contributions and improvements.
The above is the detailed content of How Can I Create a Secure Image Upload Script?. For more information, please follow other related articles on the PHP Chinese website!