PHP - Multiple file upload stuck at 20 items - php

I'm trying to setup a multiple image uploader and whenever I try and upload more than 20 files, only the first 20 files are uploaded.
Before I continue, id just like to say that max_file_uploads in php.ini is setup to 400, so other answers to very similar questions do not seem to resolve my problem.
My full code is below, please note I know I am using mysql_query, but this is just for local testing purposes.
-
PHP
if(isset($_POST['upload'])){
include("SimpleImage.php");
echo count($_FILES['file']['name']);
for($i=0; $i<count($_FILES['file']['name']); $i++) {
$allowedExts = array("gif", "jpeg", "jpg", "png", "JPG");
$extension = end(explode(".", $_FILES["file"]["name"][$i]));
date_default_timezone_set('Europe/London');
$date = date_create();
if ((($_FILES["file"]["type"][$i] == "image/gif")
|| ($_FILES["file"]["type"][$i] == "image/jpeg")
|| ($_FILES["file"]["type"][$i] == "image/jpg")
|| ($_FILES["file"]["type"][$i] == "image/png"))
&& ($_FILES["file"]["size"][$i] < 10485760)
&& in_array($extension, $allowedExts)){
$name = date_timestamp_get($date) . "_" . mt_rand() . "." . $extension;
if ($_FILES["file"]["error"][$key] > 0){
$messages[] = "Return Code: " . $_FILES["file"]["error"][$i] . "<br>";
}else{
$imagethumbTrueLocation = "../../gallery/thumb/" . $name;
$imagelargeTrueLocation = "../../gallery/photos/" . $name;
$imagethumb = new SimpleImage();
$imagethumb->load($_FILES["file"]["tmp_name"][$i]);
$imagethumb->resizeToWidth(230);
$imagethumb->save($imagethumbTrueLocation);
$imagethumblocation = "thumb/" . $name;
$imagelarge = new SimpleImage();
$imagelarge->load($_FILES["file"]["tmp_name"][$i]);
$imagelarge->resizeToWidth(800);
$imagelarge->save($imagelargeTrueLocation);
$imagelargelocation = "photos/" . $name;
$queryresult = mysql_query("INSERT INTO gallery (thumbnail, highres) VALUES ('$imagethumblocation', '$imagelargelocation')") or die(mysql_error());
if(!$queryresult) {
$messages[] = "Failed to insert record into the database.";
}else{
$messages[] = "Record sucessfully added to the database.";
}
}
}else{
$messages[] = "Invalid file";
}
}
}
HTML
<form action="#" method="post" enctype="multipart/form-data">
<input type="file" name="file[]" id="file" multiple>
<input type="submit" name="upload" value="Upload" />
</form>

I know you mentioned the max_file_uploads but could it be the case that 400 isnt recognised try 99? The only reason I say this is its a specific number 20! every time there must be a limit. Also have you checked apache config there may be a limit in there as well
I would personally fire these off with javascript so each upload has their own thread so to speak and you would be able to work round the limit if there is any.

Turns out my host has set their own limit on this which means only VPS and Dedicated accounts can change this value :(

If you are using Wamp, go on localhost page, and click on phpinfo(); in the left bottom corner.
If not you can use the function in a php file.
you will see : "Loaded Configuration File" column, to find your php.ini
Because there are multiple php.ini (one in php folder and the other in apach folder).
When done, you can verify it in phpinfo() again, just CTRL + F and look for "max_file_uploads".
Hope it will help.

Open the php.ini configuration file and change the
;Maximum number of files that can be uploaded via a single request
max_file_uploads =
to the number of files you want apache to handle on POST events.
The default value is 20.

Related

prevent uploading of large and unsupported files in image upload form

i have a php form with an image upload option as follows
<input type="hidden" name="old_picture" value="<?php if (!empty($old_picture)) echo $old_picture; ?>" />
<label for="new_picture">Picture:</label>
<input type="file" id="new_picture" name="new_picture" />
and php script something like
if (!empty($new_picture)) {
if ((($new_picture_type == 'image/gif') || ($new_picture_type == 'image/jpeg') || ($new_picture_type == 'image/pjpeg') ||
($new_picture_type == 'image/png')) && ($new_picture_size > 0) && ($new_picture_size <= MM_MAXFILESIZE) &&
($new_picture_width <= MM_MAXIMGWIDTH) && ($new_picture_height <= MM_MAXIMGHEIGHT)) {
if ($_FILES['file']['error'] == 0) {
// Move the file to the target upload folder
$target = MM_UPLOADPATH . basename($new_picture);
if (move_uploaded_file($_FILES['new_picture']['tmp_name'], $target)) {
// The new picture file move was successful, now make sure any old picture is deleted
if (!empty($old_picture) && ($old_picture != $new_picture)) {
#unlink(MM_UPLOADPATH . $old_picture);
}
}
else {
// The new picture file move failed, so delete the temporary file and set the error flag
#unlink($_FILES['new_picture']['tmp_name']);
$error = true;
echo '<p class="error">Sorry, there was a problem uploading your picture.</p>';
}
}
}
else {
// The new picture file is not valid, so delete the temporary file and set the error flag
#unlink($_FILES['new_picture']['tmp_name']);
$error = true;
echo '<p class="error">Your picture must be a GIF, JPEG, or PNG image file no greater than ' . (MM_MAXFILESIZE / 1024) .
' KB and ' . MM_MAXIMGWIDTH . 'x' . MM_MAXIMGHEIGHT . ' pixels in size.</p>';
}
}
every thing works fine but problem occurs when as a test i tried to upload a .zip file the image was not loaded but it flushed my database. all the entries for that user were deleted.
now i want a some suggessions about how to prevent this
thanks in advance
On the client side, there is not much you can do that you can actually rely on. But it can help prevent accidental problems.
Add this attribute to the file upload control to limit file types: accept="image/gif, image/jpeg"
Your validation needs to happen on server side if you want to be sure about what you are getting.
Check $_FILES['uploadctl']['size'] for the size of the file and see if it exceeds your limits.
You can force php to limit what size file uploads it accepts by setting upload_max_filesize in php.ini. Default for this is pretty low.
You cant really trust that the extension of an uploaded file is actually correct. Just because it says .jpg doesn't mean it really is. If all you are accepting is images, you should be able to verify the mimetype with getimagesize(). If you are accepting a larger range of files, check the file with Fileinfo.
If the entries in the database were deleted, you probably have a logic problem in code that you are not showing here.

Images upload error

I'm having the following problem. I use input form with four validated text input fields (not allowed to be empty), and three file input fields below on the same form. When I try to upload images which are smaller in size, everything works ok. But when I choose a larger pictures, like 1MB or so, I get the validation error on text input fields even though I filled them.
$ime = mysql_real_escape_string($_POST['ime']);
$mesto = mysql_real_escape_string($_POST['mesto']);
$telefon = mysql_real_escape_string($_POST['telefon']);
$emajl = mysql_real_escape_string($_POST['emajl']);
$opis = mysql_real_escape_string($_POST['opis']);
if ((empty($ime)) || (empty($mesto)) || (empty($telefon)) || (empty($emajl))){echo "Moraju biti uneti podaci u obavezna polja"; exit;}
//unos slike1
if ((($_FILES["slika1"]["type"] == "image/gif")
|| ($_FILES["slika1"]["type"] == "image/jpeg")
|| ($_FILES["slika1"]["type"] == "image/jpg")
|| ($_FILES["slika1"]["type"] == "image/pjpeg")
|| ($_FILES["slika1"]["type"] == "image/x-png")
|| ($_FILES["slika1"]["type"] == "image/png"))
&& ($_FILES["slika1"]["size"] < 2097152))
{
if ($_FILES["slika1"]["error"] > 0)
{
echo "Greška: " . $_FILES["slika1"]["error"] . "<br>";
}
else
{
$razdvajanje = explode('.',$_FILES['slika1']['name']);
$ekstenzija = $razdvajanje[1];
$novoime = mysql_real_escape_string($razdvajanje[0]).'_'.time();
$putanja = 'uploads/' . $novoime . "." . $ekstenzija;
move_uploaded_file($_FILES['slika1']['tmp_name'], $putanja);
}
}
else
{
echo "Slika mora biti manja od 2MB i u adekvatnom formatu";
The error I get is "Moraju biti uneti podaci u obavezna polja" even the field is not empty. When I try to upload just one larger image, it also works. It's only not working when I try to upload three 1MB images at the same time.
Just to be clear. Script is working on localhost (XAMPP). I am having issues when uploading to my web hosting server. Also, the script is working when I upload 3 image files that are around 300kb, but when I try to upload 3 files that are around 1MB in size, the process fail at around 60%. I don't think that problem is in size, but in upload time.
You have to set the filesize and override the default size set by PHP:
Something like this:
$size1=$_FILES["uploaded_file"]["size"]/1024;
$max_allowed_file_size = 50000;
if($size1 >= 0)
{
if($size1> $max_allowed_file_size )
{
$err[]= "\n Size of file should be less than $max_allowed_file_size";
}
}
Just modify your script with the filesize and you should be fine.
Do this:
Search your php.ini. (mine is under /etc/php5/apache2/php.ini)
Edit "post_max_size" to 5M
Edit "upload_max_filesize" to 5M
Edit "max_file_uploads" to 20 (<- this value determines how many files can be uploaded using a single request.)
Hope this helps.
maybe you need to increase the size allowed in php.ini
or do something like this
ini_set('post_max_size', '10M');
ini_set('upload_max_filesize', '10M');
ini_set('max_file_uploads', '20');
I solved a problem by limiting image size to 500kb. It works now. I mean, I did not solve the problem, I avoided it.

Bypassing forms input fields to upload unwanted files

My website having uploading profile image section for members and i've used the following code.
Form Code
<form action="send.php" method="post" enctype="multipart/form-data" name="send" id="send">
Your Image : <input type="file" name="pic" id="pic"/>
<input type="Submit" name="Submit" value="Submit"/>
</form>
PHP Code send.php
$ImageName = $_FILES[pic][name];
if(!empty($ImageName) && $_FILES[pic][type] == "image/jpeg" || $_FILES[pic][type] == "image/png" || $_FILES[pic][type] == "image/gif" || $_FILES[pic][type] == "image/bmp"){
$t = time();
$NewImageName = "$t$ImageName"; // image new name
copy($_FILES[pic][tmp_name], "users/$NewImageName"); // copy it to directory
} else {
echo "no upload done";
}
But someone by using firefox extension manage to bypass it and uploaded php file
Who uploaded the file to my website sent me message said "you only check for type !"
and said " i used firefox extension that can fake input fields and passed PHP file ".
So my question how do i protect my image upload form of the above code ? ~ thanks
First I don't think that's is the valid format to read $_FILE variable
$ImageName = $_FILES[pic][name];
You should use
$ImageName = $_FILES['pic'][name];
Then I think it is improbable that someone can fake a server side check.
Try to hack this, I use a *PATHINFO_EXTENSION* as mentioned in PHP.net Manual
$validFormat = array("jpg","JPG","jpeg","JPEG","png","PNG","gif","GIF");
$path = pathinfo($_FILES['pic']['name'], PATHINFO_EXTENSION);
if(in_array($path, $validFormat)){
// it's okay
}else{
// Error
}
I'm working with this code since I discovered pathinfo a while ago and nobody hack it..
The "type" entries in the $_FILES array are indeed just values that the client sent. Do not trust them.
files are executed as php not based on the MIME type given by the client (or the MIME type that is recognized from their data), but simply by their extension.
$imageName = $_FILES['pic']['name'];
if (isset($imageName)) {
$ext = pathinfo($imageName, PATHINFO_EXTENSION);
if (in_array(strtolower($ext), array('jpg', 'jpeg', 'gif', 'png', 'bmp')) {
$t = time();
$newImageName = $t . basename($imageName);
copy($_FILES['pic']['tmp_name'], 'users/' . $newImageName);
}
} else {
echo 'no upload done';
}
Note the invocation to pathinfo to get the extension, and basename to avoid path traversal attacks.

Problem with PHP (works on localhost, but errors on web server)

am having some trouble with PHP on the webserver I am using.
I am sure the answer is obvious but for some reason it is eluding me completely.
I have a php file which uploads two files, a before and an after shot of the client.
The script on my server(localhost) works fine, it uploads the files, renames the files to a timestamp and puts the images into there folders for further sorting by another script.
Yet when I upload it to the webserver, and some files work (i.e mel.jpg, test.jpg) but files like IMG_0042.jpg do not work, Im sure the answer is something simple, but is completely eluding me.
Im thinking the underscore may have something to do with it, but cannot for the life of my figure it out, any help greatly appreciated,
thanks very much.
<?php
if(!isset($_COOKIE['auth'])) {
header("Location: login12.php");
exit();
}
$page_title="test";
include('header.html');
// Upload and Rename File
if (isset($_POST['submitted'])) {
$filenamebef = $_FILES["uploadbef"]["name"];
$filenameaft = $_FILES["uploadaft"]["name"];
$file_basename_bef = substr($filenamebef, 0, strripos($filenamebef, '.'));
$file_basename_aft = substr($filenameaft, 0, strripos($filenameaft, '.'));
// get file extention
$file_ext_bef = substr($filenamebef, strripos($filenamebef, '.'));
$file_ext_aft = substr($filenameaft, strripos($filenameaft, '.'));
// get file name
$filesize_bef = $_FILES["uploadbef"]["size"];
$filesize_aft = $_FILES["uploadaft"]["size"];
$allowed = array('image/pjpeg','image/jpeg','image/JPG','image/X-PNG','image/PNG','image /png','image/x-png');
if ((in_array($_FILES['uploadbef']['type'], $allowed)) && in_array($_FILES['uploadaft']['type'], $allowed)) {
if (($filesize_bef < 200000) && ($filesize_aft < 200000)){
// rename file
$date = date("mdy");
$time = date("His");
$timedate = $time . $date;
$newfilenamebef = $timedate . $file_ext_bef;
$newfilenameaft = $timedate . $file_ext_aft;
if ((file_exists("upload/images/before" . $newfilenamebef)) && (file_exists("uploads/images/after" . $newfilenameaft))) {
// file already exists error
echo "You have already uloaded this file.";
} else {
move_uploaded_file($_FILES["uploadbef"]["tmp_name"], "uploads/images/before/" . $newfilenamebef) && move_uploaded_file($_FILES["uploadaft"]["tmp_name"], "uploads/images/after/" . $newfilenameaft);
echo "File uploaded successfully.";
}
}
} elseif ((empty($file_basename_bef)) && (empty($file_basename_aft))) {
// file selection error
echo "Please select a file to upload.";
} elseif (($filesize_bef > 200000) && ($filesize_aft > 200000)) {
// file size error
echo "The file you are trying to upload is too large.";
} else {
// file type error
echo "Only these file typs are allowed for upload: " . implode(', ',$allowed);
unlink($_FILES["uploadbef"]["tmp_name"]);
unlink($_FILES["uploadaft"]["tmp_name"]);
}
}
echo $newfilenamebef;
echo $newfilenameaft;
?>
<form enctype="multipart/form-data" action="uploading.php" method="post">
<input type="hidden" value="MAX_FILE_SIZE" value="524288">
<fieldset>
<legend>Select a JPEG or PNG image of 512kb or smaller to be uploaded : </legend>
<p><b>Before</b> <input type="file" name="uploadbef" /></p>
<p><b>After</b> <input type="file" name="uploadaft" /></p>
</fieldset>
<div align="center"><input type="submit" name="submit" value="Submit" /></div>
<input type="hidden" name="submitted" value="TRUE" />
</form>
<?php
include('footer.html');
?>
You should but these two lines at the top of your index.php or bootstrap.php :
error_reporting( -1 );
ini_set( "display_errors" , 1 );
And see if some error messages turn up.
It is quite possible that problem is caused by wrong file permissions.
At a quick guess I would say that your localhost is not case sensitive, whereas your webserver is.
In other words, on your localhost IMG_12345.JPG is the same as img_12345.jpg. On your webserver, though, they are treated differently.
Without any actual reported errors, it's hard to be certain, but this is a common problem.
You're not checking for valid uploads properly. Something like the following would be FAR more reliable:
// this value is ALWAYS present and doesn't depend on form fields
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errmsgs = array();
if ($_FILES['uploadbef']['error'] !== UPLOAD_ERR_OK) {
$errs++;
$errmsgs[] = "'uploadebef' failed with code #" . $_FILES['uploadebef']['error'];
}
if ($_FILES['uploadaft']['error'] === UPLOAD_ERR_OK) {
$errs++;
$errmsgs[] = "'uploadeaft' failed wicode #" . $_FILES['uploadeaft']['error'];
}
if (count($errmsgs) > 0) {
print_r($errmsgs);
die();
}
... process the files here ...
}
As well, why re-invent the wheel to split up the file names?
$parts = path_info($_FILES['uploadaft']['name']);
$basename = $parts['basename'];
$ext = $parts['extension'];

problem with uploading the images with php file upload

hi guys i am uploading the images using the #PhP file upload Method # If i upload 10 Images at a time (Each Images is 2000 /3000 dimension). then the on click save function is not working. if i upload 5 images or less than five images then its working fine wats wrong with my coding i just include my php code with this post <input value="Save" type="submit" name="SubSave" id="SubSave" onClick="return changes();">
if($_POST['SubSave'] == "Save"){
$aid = $_GET['rid'];
$updcount = $_POST['theValue'];
if($_SESSION["almgtype"]==1 || (GetUserNoPhoto($_SESSION["almgid"]))>(GetTotalPhotoCount1($_SESSION["almgid"],$aid))) {
$uid = $_SESSION["almgid"];
for($k=1;$k<=$updcount;$k++) {
//echo $k;
echo $_FILES["uploadfile"]["type"];
if($_FILES["uploadfile".$k]["name"]!="") {
if(($_FILES["uploadfile".$k]["type"] == "image/gif") || ($_FILES["uploadfile".$k]["type"] == "image/jpeg")|| ($_FILES["uploadfile".$k]["type"] == "image/pjpeg") || ($_FILES["uploadfile".$k]["type"] == "image/png")) {
if ($_FILES["uploadfile".$k]["error"] > 0)
{
echo "Error: " . $_FILES["uploadfile".$k]["error"] . "<br />";
}
else
{
move_uploaded_file($_FILES["uploadfile".$k]["tmp_name"],
"photoalbum/" . $_FILES["uploadfile".$k]["name"]);
$uploadfile = "photoalbum/" . $_FILES["uploadfile".$k]["name"];
}
$path = $uploadfile;
$checklist = "select * from amt_photos1 where aid = '".trim($aid)."' and uid = '".trim($uid)."' and path = '".trim($path)."'";
$chkresult = mysql_query($checklist);
if(mysql_num_rows($chkresult) == 0) {
$i = 0;
$path =$uploadfile;
$result = "insert into amt_photos1 set uid = '".trim($uid)."',
aid = '".trim($aid)."',
path = '".trim($path)."',
status = '0',
createdby = '".$_SESSION["almgid"]."',
createddate = now()";
$rowlist = mysql_query($result) or die("Error:(".mysql_error().")".mysql_error());
}
/********************** if file already exist means ******************************************/
else {
$err= "The Uploaded file name ".$path." Is already exisit in the Album. Rename It or try to add Any other Photos";
}
/********************** if file already exist means ******************************************/
$path ="";
$uploadfile = "";
$i = "";
} // file extention
else {
$err= "Unable To Upload The File Please Check The File Extention.Try Again Later";
}
}
}
}
} // if save close
You probably need to change the maximum POST size in your php.ini configuration file (post_max_size setting).
You can use the command phpinfo() to dump your configuration. Likely, as others have stated you need to increase the upload size and execution time.
These can be modified through a .htaccess file.
php_value upload_max_filesize 20M
php_value post_max_size 20M
php_value max_execution_time 200
php_value max_input_time 200
Just as a warning: Your upload handling script will make it utterly trivial to completely subvert your server:
You blindly trust that the $_FILES[...]['type'] value is correctly set - this value is completely under the user's control, and they can stuff in "image/jpeg" and upload any type of file they want
You blindly trust that the $_FILES[...]['filename'] value is correctly set - again, this value is completely under the user's control, and they can stuff in "hackme.php" if they want to
You blindly write the file to your photoalbum directory, but don't check if the user-supplied filename contains pathing data
So, what happens if someone uploads the following file:
$_FILES['uploadfile0']['type'] = 'image/gif';
$_FILES['uploadfile0']['filename'] = '../pwn_me.php';
You've now happily put a user-provided PHP script ONTO YOUR WEBSERVER and they can now do anything they want.
On top of that, your database queries blindly insert the same data into the queries, leaving you wide open to SQL injection attacks. As well, you don't check for filename collisions until AFTER you've moved the file. So, someone could upload a malicious script, but only do it once for that particular filename. Congratulations, you've implemented versioned attacks on your server. You'll have "pwn_me.php", "pwn_me2.php", "pwn_me3.php", "my_little_pwnme.php", and so on.

Categories