Processing PHP ERROR forms when loading an image

I use HTML to upload images and process forms in PHP in my form, I need the following

  • Maximum file size: 5 files. User can upload
  • I need to save the entire image name in an SQL database.

HTML

<input type="file" id="files" name="files[]" multiple/> 

SCRIPT

 <script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { if (window.File && window.FileList && window.FileReader) { $("#files").on("change", function(e) { var files = e.target.files, filesLength = files.length; for (var i = 0; i < filesLength; i++) { var f = files[i] var fileReader = new FileReader(); fileReader.onload = (function(e) { var file = e.target; $("<img></img>", { class: "imageThumb", src: e.target.result, title: file.name }).insertAfter("#files"); }); fileReader.readAsDataURL(f); } }); } else { alert("Your browser doesn't support to File API") } }); </script> 

FORM PROCESSING

 $file = filter_input(INPUT_POST, 'file', FILTER_SANITIZE_STRING); $file1 = filter_input(INPUT_POST, 'file1', FILTER_SANITIZE_STRING); $file2 = filter_input(INPUT_POST, 'file2', FILTER_SANITIZE_STRING); $file3 = filter_input(INPUT_POST, 'file3', FILTER_SANITIZE_STRING); $file4 = filter_input(INPUT_POST, 'file4', FILTER_SANITIZE_STRING); 

with the code above, I need to save the image name in the SQL database

+5
source share
5 answers

Edited again to reflect posters in new wishes on how the user should look. Now there is a drag and drop with a preview or manual selection of 5 files. The drag and drop is sent by an ajax message, so keep an eye on the console for the result. The display and stream should be streamlined, but shows a technical working example. The same PHP code handles both results.

 <html> <body> <pre><? print_r($_FILES); //SHOW THE ARRAY foreach ($_FILES as $file) { if (!$file['error']) { //PROCESS THE FILE HERE echo $file['name']; } } ?></pre> <script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script> <script type="text/javascript"> var fd = new FormData(); $(document).ready(function() { //submit dragdropped by ajax $("#dropsubmit").on("click", function(e) { $.ajax({ data: fd, processData: false, contentType: false, type: 'POST', success: function(data){ //FILES POSTED OK! REDIRECT console.log(data); } }); }) var dropzone = $("#dropzone"); dropzone.on('dragenter', function (e) { $(this).css('background', 'lightgreen'); }); //dropped files, store as formdata dropzone.on('dragover', stopPropagate); dropzone.on('drop', function (e) { stopPropagate(e) $(this).css('background', 'white'); var files = e.originalEvent.dataTransfer.files; for (var i = 0; i < files.length; i++) { preview(files[i]) fd.append('file' + (i + 1), files[i]); if (i >= 5) continue } }); function stopPropagate(e) { e.stopPropagation(); e.preventDefault(); } if (window.File && window.FileList && window.FileReader) { $("input[type=file]").on("change", function(e) { preview(e.target.files[0]) }); } else { alert("Your browser doesn't support to File API") } function preview(item) { var fileReader = new FileReader(); fileReader.onload = (function(e) { var file = e.target; $("<img></img>", { class: "imageThumb", src: file.result, title: file.name, }).appendTo("#images"); }); fileReader.readAsDataURL(item); } }); </script> <div id="dropzone" style="width:100px;height:100px;border:2px dashed gray;padding:10px">Drag & Drop Files Here</div> <input type="button" id="dropsubmit" value="Submit dropped files" /> <hr> <form method="post" enctype="multipart/form-data"> <input id="file1" name="file1" type="file"/><br> <input id="file2" name="file2" type="file"/><br> <input id="file3" name="file3" type="file"/><br> <input id="file4" name="file3" type="file"/><br> <input id="file5" name="file3" type="file"/><br> <input name="submit" type="submit" value="Upload files" /> </form><div id="images"></div> </body> </html> 
+1
source

You should use code like this in your PHP

 $conexion = mysqli_connect("Servername", "usernameDB", "PasswordDB", "nameDB"); if (isset($_FILES['files'])) { if (sizeof($_FILES['files']['tmp_name']) > 5) { exit("max 5 files allowed"); } foreach ($_FILES['files']['error'] as $key => $value) { switch($value) { case (0): if (exif_imagetype($_FILES['files']['tmp_name'][$key])) { $dome_dir = "imaged/uploaded/"; // do something with the file, for example move it. move_uploaded_file($_FILES['files']['tmp_name'], $some_dir . $_FILES['name']); $message = "is a image... Uploaded"; // take care, if the name are equals that something storaged, will overwrite the old file $filename = mysqli_real_string_escape($conexion, $_FILES['files']['name'][$key]); $store_image = $some_dir . $filename; $sql = "INSERT INTO tablename(ID, IMAGE_ROUTE) VALUES(NULL, '$store_image')"; if(mysqli_query($conexion, $sql)){ echo 'Image ' . $_FILES['files']['name'][$key] . ' saved successful'; } else { echo "An error has ocurred with the database saving the image"; } } else { $message = "isn't a image"; } break; case 1: $message = 'is too big'; break; case 2: $message = 'is too big'; break; case 3: $message = "wasn't uploaded complete"; break; case 4: $message = "wasn't uploaded"; break; default: $message = "Error: file wasn't uploaded"; break; } echo "The file name: " . $_FILES['files']['name'][$key] . ' ' . $message . '<br>'; } } 

And your HTML puts something like this

 <form id="form" method="post" enctype="multipart/form-data"> <input type="file" name="files[]" multiple> <input type="submit" value="Submit"> </form> 

In JS put something like this

 $(document).ready(function() { $('#form').on('submit', function(e) { var $fileUpload = $("input[type='file']"); if (parseInt($fileUpload.get(0).files.length)>5){ e.preventDefault(); alert("You can only upload a maximum of 5 files"); } else if (parseInt($fileUpload.get(0).files.length) == 0) { e.preventDefault(); alert("Choose almost one file"); } }); }); 

Hope this helps you :)

+2
source

Perhaps you expect the user to do this several times:

press browse button> select file> file is displayed

But the way to work with multiple files is that you select several files in the file browser once (holding down CTRL). These are the files that are passed to the $ _FILE variable. I do this several times, only the last file transferred passes

edit: if you want to clarify this for the user, you must remove all image tags in each file view event, so that only the one that was last selected is displayed

to reflect this:

 <html> <body> <pre><? foreach ($_FILES['files']['name'] as $fileName ) { echo $fileName."\n"; } ?></pre> <form method="post" enctype="multipart/form-data"> <input name="files[]" type="file" /> <input name="submit" type="submit" /> </form> </body> </html> 
+1
source

This code does not allow downloading more than 5 files. Here the trick is to reset the input type file, this is what you just cloned and replaced the previous one. I tried with this.reset , but the text of the number of added files remained.

  if (window.File && window.FileList && window.FileReader) { $("#files").on("change", function(e) { var files = e.target.files; var filesLength = files.length; var allowedCnt = 5; if (filesLength > allowedCnt) { $(this).replaceWith($(this).val('').clone(true)); alert('Can not add more then ' + allowedCnt + ' files'); return false; } else { for (var i = 0; i < filesLength; i++) { var f = files[i] var fileReader = new FileReader(); fileReader.onload = (function(e) { var file = e.target; $("<img></img>", { class: "imageThumb", src: e.target.result, title: file.name }).insertAfter("#files"); }); fileReader.readAsDataURL(f); } } }); } else { alert("Your browser doesn't support to File API") } 

HTML

 <form method="POST" action="" id="myform" enctype="multipart/form-data"> <input type="file" id="files" name="files[]" multiple /><br /> <input type="submit" name="submit" value="submit" /> </form> 

PHP Here, just connect to the database and add the elements to the table as you want using the foreach loop. Of course, you can also check or check on the server side.

 if (isset($_POST["submit"])) { $link = mysqli_connect("myhost", "myuser", "mypassw", "mybd") or die("Error " . mysqli_error($link)); foreach (array_keys($_FILES['files']['tmp_name']) as $key) { //Moving file where you want. mysqli_query($link, "INSERT INTO tblName (fieldName) VALUES ('" . mysqli_real_escape_string($_FILES["files"]['name'][$key]) . "')"); } } 
+1
source

Source: https://habr.com/ru/post/1203544/


All Articles