Images upload error - php

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.

Related

php Maximum size upload not validating properly

if(!empty($employeepic)) {
if ((($employeepic_type == 'image/jpg') ||($employeepic_type == 'image/jpeg') ||($employeepic_type == 'image/gif') ||
($employeepic_type == 'image/png')) && ($employeepic_size <= EMP_MAXSIZE) && ($employeepic_size > 0)){
// Move the file to the target upload folder
$target = (EMP_UPLOADPATH .$firstname.$employeepic);
if(move_uploaded_file($_FILES['employeepic']['tmp_name'],$target)){
$employee = $firstname. " " .$lastname;
}
}else{
$filetoobig =' <p class="error"> There was a problem uploading your picture. Maximum size is 30K and must be in jpg, jpeg or pjpeg format</p>';
#unlink($_FILES['employeepic']['tmp_name']);
}
}
Can anyone see why the validation of file size not working?
(EMP_MAXSIZE = 32768)
Edit: The limit size is set at 32768 but can still upload 2MB files
Edit: The code to assign Employee_pic Size:
$employeepic = mysqli_real_escape_string($dbc, trim($_FILES['employeepic']['name']));
$employeepic_type = $_FILES['employeepic']['type'];
$employeepic_size = $_FILES['employeepic']['size'];
I figured it out. I am probably not doing the "right way of coding" but it nevertheless fixed the problem. I created another variable called $employee_pic = $firstname.$employeepic; in the true section of my validation and added "employee_pic='' ;" under the false result of my validation in order not to save the picture to mysql. This was accomplished by changing the $employeepic variable for $employee_pic in my insert query.

PHP uploading issues

I'm having strange issues when uploading to the server via PHP.
I get the type of the file (working properly, it shows them via echo)
$file = $_FILES['file'];
$typeFile = end(explode(".", $file['name']));
Then I make some comparasions to let them upload it or not, here are the fille types allowed
if($file['size'] <= 52428800) { //50MB, and my file is about 2,5MB
if($fileType == "nlpack" || $fileType == "nl2pkg" || $fileType == "nlpark") {
$id = add_to_db($file['name']); //Adding to database the name, this will return an id, it works
if($id) {
mkdir("uploads/".$id); //create a folder where to add the file, working fine!
if(move_uploaded_file($file['tmp_name']), ".uploads/".$id."/".$file['name']) {
echo "file uploaded correctly";
}
else {
echo "has been an error"; //it enters here, while the other file types enters in the if()
}
}
else {
echo "Has been an error";
}
} else {
//alert an error
}
}
The thing is, that "nlpack" file type doesn't uploads, and it enters the if() because I checked it with echos, while the other two are uploaded without problem.
I also check the file size, but that's running fine.
Any ideas of what is going on?
Thanks in advance
Make sure the filesize isn't exceeding the settings in your php.ini or the file will just fail to upload.
upload_max_filesize integer
The maximum size of an uploaded file.
When an integer is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used.
AND if muliple:
max_file_uploads integer
The maximum number of files allowed to be uploaded simultaneously. Starting with PHP 5.3.4, upload fields left blank on submission do not count towards this limit.

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.

PHP - Multiple file upload stuck at 20 items

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.

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