problem with uploading the images with php file upload - php

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.

Related

PHP - limit the file size but somehow got Warning: POST Content-Length exceeds the limit

I wanted to test out the file upload code. This is an upload file code and it has the option whether the user has the file to upload or just submit it blankly. I added the error message to limit the file extension. It works.
Then, I added an error message to notify the user about the limit file size. But somehow got the Warning: POST Content-Length of 681075903 bytes exceeds the limit of 8388608 bytes in Unknown on line 0
instead of the error message of "Sorry, your file is too large. Only 3MB allowed" from the php code.
<html><head></head>
<body>
<form method="post" action="" enctype="multipart/form-data">
Upload File:
<input type="file" name="upload" /><br>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
<?php
include("config.php");
if(isset($_POST['submit']) ){
//user has the option whether to upload the file or not
if ($_FILES['upload']['size'] != 0 ){
$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);
$allowed = array('zip','rar', 'pdf', 'doc', 'docx');
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(in_array($ext, $allowed)){
if($filesize > 3000000) {
$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filedata','$filetype','$filesize')" ;
if ($con->query($query) == TRUE) {
echo "<br><br> New record created successfully";
} else {
echo "Error:<br>" . $con->error;
}
}
else{
echo "Sorry, your file is too large. Only 3MB allowed";
}
}
else{
echo "Sorry, only zip, rar, pdf, doc & docs files are allowed.";
}
//if user has no file to upload then proceed to this else statement
} else {
$filename = $con->real_escape_string($_FILES['upload']['name']);
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);
$query = "INSERT INTO contracts(`filename`, `filetype`,`filesize`) VALUES ('$filename','$filetype','$filesize')" ;
if ($con->query($query) == TRUE) {
echo "<br><br> New record created successfully";
} else {
echo "Error:<br>" . $con->error;
}
}
$con->close();
}
?>
I don't get it. What did I do wrong in this code?
I think it is the if ($_FILES['upload']['size'] != 0 ){ part that gave the problem but I still want my user to have it optional to upload.
Its not a problem with your code. The http request isnt going through php because of the post max size setting.
Find this line in your php.ini of the server and change it:
; http://php.net/post-max-size
post_max_size = [max uploadsize like '32M' or '1G']
Can you post the form HTML code ?
The problem is, php has a directive (post_max_size) that limits the size of what he allows in POST - before any execution of your script. So, if this limit is reached, the warning is emitted before your script is called, and $_POST is not filled in.
It would deserves additional testing, but be sure :
to include MAX_FILE_SIZE hidden field in your form (see http://php.net/manual/en/features.file-upload.post-method.php).
to set post_max_size to something largely greater to what you want to accept
to set upload_max_filesize to (at first sight) the value you want.
In addition, it would also be intersting to try setting the maxlength attributes on the input, as this is is stated in the RFC-1867.
If the INPUT tag includes the attribute MAXLENGTH, the user agent should consider its value to represent the maximum Content-Length which the server will accept for transferred files.
In this way, servers can hint to the client how much space they have available for a file upload, before that upload takes place. It is important to note, however, that this is only a hint, and the actual requirements of the server may change between form creation and file submission.
This would allow to forbid the upload directly in the browser that respect the RFC.

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.

Video Uploads in PHP, can't find upload directory?

im using this php video upload script. i have set my directory path to a folder called video which i have created with the same directory as the php file. But i can not find the video being uploaded.
It is not going to the directory i have asked it to? Why is this can someone please help me.
I am not receiving any errors.
Thanks.
HTML:
<form action="upload_videos_process.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="uploadFile" id="uploadFile" />
<br />
<input type="submit" name="submit" value="Upload File" />
</form>
php file:
<?php
//This handles the maximum size for the video file in kbs
define ("MAX_SIZE","500");
//This function reads the extension of the file to ensure that it is an video file
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
//This variable handles an error and won't upload the file if there is a problem with it
$errors=0;
//checks if the form has been submitted
if(isset($_POST['Submit']))
{
//reads the name of the file the user submitted for uploading
$video=$_FILES['video']['name'];
//if it is not empty
if ($video)
{
//get the original name of the file from the clients machine
$video_filename = stripslashes($_FILES['video']['name']);
$video_extension = getExtension($filename);
$video_extension = strtolower($extension);
//if it is not a known extension, we will suppose it is an error and will not upload the file, otherwise we will do more tests
if (($video_extension != "mpeg") && ($video_extension != "avi") && ($video_extension != "flv") && ($video_extension != "mov"))
{
echo '<h1>Unknown extension!</h1>';
$errors=1;
}
else
{
//get the size of the video
$size=filesize($_FILES['video']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}
//give the video a unique name in case a video already exists with the name on the server
$video_name=time().'.'.$extension;
//assign a folder to save the video to on your server
$newname="video/".$video_name;
//verify that the video has been loaded
$copied = copy($_FILES['video']['tmp_name'], $newname);
if (!$copied)
{
echo '<h1>Copy unsuccessful!</h1>';
$errors=1;
}}}}
//If no errors registered, print the success message
if(isset($_POST['Submit']) && !$errors)
{
echo "<h1>File Uploaded Successfully! Try again!</h1>";
}
?>
You've blindly assumed everything's working perfectly. Things fail. First step: check if the upload actually did anything:
if ($_FILES['video']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['video']['error']);
}
The error codes are defined here: http://php.net/manual/en/features.file-upload.errors.php
As well, don't use copy() on the upload file, once you've verified the upload succeeded. There's move_uploaded_file() for a reason - it has extra security checks to ensure that the file hasn't been tampered with on the server, and it actually MOVES the file. copy() can kill performance, especially on large files, since you're duplicating the file, instead of just doing some filesystem housekeeping.
You're also trusting the user to not tamper with the filename. There is NOTHING to prevent a malicious user from doing ren nastyvirus.exe cutekittens.avi before uploading, and your script will happily accept that .exe, because its filename has simply been changed. Use server-side mime-detection (e.g http://www.php.net/manual/en/book.fileinfo.phpenter link description here) to get around this. NEVER trust ANYTHING from a user.
It might be because your php configuration does not allow to upload big files. Try setting
upload_max_filesize = 500M
or even larger than 500M in php.ini & also as ppl mention here in comments, enable the errors
ini_set('display_errors', 1);
ini_set('error_reporting', 8191);

php file upload error of 1 - What is correct way to use php_ini?

I'm having issues uploading a pdf to my server. The upload_max_filesize is 2M and the file(s) are more then that, around 4M. I found a post with a similar issue to mine here
$_FILE upload large file gives error 1 even though upload_max_size is bigger than the file size
What I can gather from php.net for the correct usage of ini_set commands is this, which I am currently using.
ini_set('upload_max_filesize', 100000000);
ini_set('post_max_size', 110000000);
ini_set('memory_limit', 120000000);
ini_set('max_input_time', 20);
But in the link I posted it seems they are using a different method (if they aren't just summarizing the correct code that is). But It seems my code isn't working as is either. I have <?php phpinfo(); ?> at the bottom of my page and it says the upload_max_filesize is still 2M. Am I using the correct syntax for ini_set? or is my issue with upload my pdfs something else?
My code handling the upload is
//======================pdf upload=====================
if ($_POST['erasePDF'] == "Yes") //checking if erase box was checked and erasing if true
{
if (file_exists($pdf))
{
unlink( $pdf );
$pdf = "";
}
}
print_r($_FILES['pdf']);
if (!empty($_FILES['pdf']['name'])) //checking if file upload box contains a value
{
$saveDirectoryPDF = 'pdfs/'; //name of folder to upload to
$tempName = $_FILES['pdf']['tmp_name']; //getting the temp name on server
$pdf = $_FILES['pdf']['name']; //getting file name on users computer
$test = array();
$test = explode(".", $pdf);
if((count($test) > 2) || ($test[1] != "pdf" && $test[1] != "doc" && $test[1] != "docx")){
echo "invalid file";
}else{
$count = 1;
do{
$location = $saveDirectoryPDF . $count . $pdf;
$count++;
}while(is_file($location));
if (move_uploaded_file($tempName, $location)) //Moves the temp file on server
{ //to directory with real name
$pdf = $location;
}
else
{
echo "hi";
echo '<h1> There was an error while uploading the file.</h1>';
}
}
}else{
$pdf = "";
}
if(isset($_POST['link']) && $_POST['link'] != ""){
$pdf = $_POST['link'];
}
//======================end of pdf upload==============
The output of the line 'print_r($_FILES['pdf']);' is
Array ( [name] => takeoutmenu.pdf [type] => [tmp_name] => [error] => 1 [size] => 0 )
Some providers does not allow you change certain values in running time. Instead of this, try to either change it in the real php.ini file or use an .htaccess (For Apache web servers) where you can add your configuration. You can find more information in the PHP.net article about this subject: How to change configuration settings.
Based on your story, example .htaccess
<IfModule mod_php5.c>
php_value upload_max_filesize 100000000
php_value post_max_size 110000000
php_value memory_limit 120000000
php_value max_input_time 20
</IfModule>

Categories