PHP Image Upload with Validation and Security Checks
This Snippet is coded by a user inOnline php Compiler. You can see and run this code too.
زبان: PHP
This PHP code handles image file uploads from a web form. It first checks if a file was submitted via $_FILES['fileToUpload']. Then it performs several validation checks to ensure the file is a legitimate image and meets security requirements before saving it to the uploads/ directory.
- Image verification: Uses
getimagesize()to confirm the file is a real image. - Duplicate file check: Rejects uploading a file with the same name if it already exists.
- Size limit: Restricts uploads to 500KB or less.
- Extension whitelist: Only allows JPG, JPEG, PNG, and GIF formats.
To use this script, include it in a form with <input type="file" name="fileToUpload"> and a submit button. Note that the code is incomplete: $uploadOk is not initialized and the last echo is truncated. Always initialize variables and complete error handling for production use.