PHP secure photo upload function
Make sure In php.ini : file_uploads = On
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
<?php /* $form_file_name: name of file field in your upload form $file_name: final uploaded file name $folder: name of upload subfolder in photo folder (i.e users, categories or products; result: photo/products) */ function upload_photo($form_file_name, $file_name, $folder) { $target_dir = 'photo/'.$folder.'/'; // name of original file to upload $target_file = $target_dir . basename($_FILES[$form_file_name]["name"]); $uploadAllowed = 'yes'; //Get file extension (i.e. jpeg) $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION); //Test image file is a real image or fake image, to secure shell upload vulnerability if (isset($_POST["submit"])) { $check = getimagesize($_FILES[$form_file_name]["tmp_name"]); // show width and height of uploaded image echo "<br />width*height: $check[0] * $check[1]<br />"; if ($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadAllowed = 'yes'; } else { echo "File is not an image."; $uploadAllowed = 'no'; } } $target_file = $target_dir . $file_name . '.' . $imageFileType; //Check if file already exists if (file_exists($target_file)) { echo "<div class='center'>File already exists.</div>"; $uploadAllowed = 'no'; } //Check if file size is less than 5000000 bytes if ($_FILES[$form_file_name]["size"] > 5000000) { echo "File size must be less than 5000000 bytes."; $uploadAllowed = 'no'; } //Allow certain file formats,it's possible to add .svg and .webp if (strtolower($imageFileType) != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "JPG, JPEG, PNG & GIF files are allowed."; $uploadAllowed = 'no'; } if ($uploadAllowed == 'no') { echo "<div class='center'>Your file was not uploaded.</div>"; } else { //When everything is OK, try to upload file chmod($target_dir, '0755'); // set permission to upload file if (move_uploaded_file($_FILES[$form_file_name]["tmp_name"], $target_file)) { echo '<div class="info">File successfully uploaded</div>'; } else { echo "<div class='center'>Error in uploading file.</div>"; } } } |
Tanks for your proffesional site.