move_uploaded_file() only uploads small files - php

I want to implement a small file upload on a web portal. I found this solution on PHP.net:
<form action='action.php' method='post' enctype="multipart/form-data">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<!-- Name of input element determines name in $_FILES array -->
Send this file:
<input name="userfile" type="file"/>
<!-- hidden input fields to sent variables to action.ph -->
<innput type="hidden" name='casenumber' id="caseForFileUpload" />
<input type="hidden" name='key' id="keyForFileUpload" />
<input type="submit" value="Send File" name="uploadfiles"/>
</form>
and this is the relevant part of action.php
if(isset($_POST['uploadfiles'])){
if(!empty($_FILES)){
$target_dir = "upload/";
$target_file = $target_dir.basename($_FILES['userfile']['name']);
$fileType = pathinfo($target_file,PATHINFO_EXTENSION);
if($fileType == "pdf"){
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $target_file)){
echo "<br><br>File uploaded";
}else{
echo "<br><br>File could not be uploaded";
}
}
}
}
This works well for small files <150KB, but fails for files larger than that and I don't know why this is happening.
Relevant info from php.ini:
upload_max_filesize = 20M
post_max_size = 20M
max_execution_time = 30
max_input_time = 60
So it really should work for files that are larger than 150KB. There is no message in the PHP log and no .htaccess is used that may override these settings.
Where else can I look to track down this behavior or how else can I implement a file upload to allow file sizes for up to 2MB?
PS: Please also note that the server is still running with PHP 5.2.17 and that it's not in my power to update it to a newer version.

As request by the OP:
name="MAX_FILE_SIZE" value="30000"
That is 30,000 bytes. As per the manual http://php.net/manual/en/features.file-upload.post-method.php
"The MAX_FILE_SIZE hidden field (measured in bytes)".
Either remove that input, or increase it.

Related

cannot get file to upload in PhP

I have added this to my form_action.php:
if(isset($_FILES['attachment1'])){
$errors= array();
$file_name = $_FILES['attachment1']['name'];
$file_size = $_FILES['attachment1']['size'];
$file_tmp = $_FILES['attachment1']['tmp_name'];
$file_type = $_FILES['attachment1']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['attachment1']['name'])));
$expensions= array("jpeg","jpg","png","doc","pdf");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG, PNG, PDF or DOC file.";
}
if(empty($errors)==true) {
move_uploaded_file($file_tmp,"uploads/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
with the form field being
<form method="post" action="form_action1.php">
<div class="form-group">
<label for="attachment1">Add file(s)</label>
<input type="file" class="form-control-file" id="attachment1" aria-describedby="fileHelp" name="attachment1">
<input type="file" class="form-control-file" id="attachment2" aria-describedby="fileHelp" name="attachment2">
<input type="file" class="form-control-file" id="attachment3" aria-describedby="fileHelp" name="attachment3">
</div>
</form>
The path gets saved but the file does not upload. Am I missing a step that I am not aware of? Also, can I set an ARRAY in the $_FILES field to allow for three uploads?
This is the last step in a personal project that I am trying to complete. Thank you.
You need to add enctype for the form to post files.
<form method="post" action="form_action1.php" enctype="multipart/form-data">
From MDN:
enctype
When the value of the method attribute is post, enctype is the MIME type of content that is used to submit the form to the server. Possible values are:
application/x-www-form-urlencoded: The default value if the attribute is not specified.
multipart/form-data: The value used for an element with the type attribute set to "file".
text/plain (HTML5): This value can be overridden by a formenctype attribute on a or element.

Form doesn't see file uploader - php

I'm attempting to build my first form/file uploader (I'm a newb fyi).
I am testing on a local server on my mac, both the form, file handler, and the uploads folder are in the same file directory with one another.
When I select a file using the submit form (test file is 'testFilego.txt' and 3 bytes in size'), i get the following error: http://localhost/PhP_exercises/__tizag/280-php-fileupload-test.php?MAX_FILE_SIZE=2500000&uploadedfile=testFilego.txt. The submit form doesn't seem to connect to the handler (?). I thought the test file would appear in my uploads folder. Help.
This is the submit form:
<form>
<form enctype="multipart/form-data" action="280-php-uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="2500000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
</form>
This is the file hander the form ought to be contacting
<?php
280-php-uploader.php&lt?php
//This is '280-php-uploader.php'
// Where the file is going to be placed
$target_path = "uploads/";
// Add the original filename to our target path.
//Result is "uploads/filename.extension"
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
As Marco Acierno observed, i'd posted the form inside a form and that seems to have caused the problem.

PHP cannot upload multiple images

I have a form in which I want to upload at most five images. The name and extension of the images are supposed to be inserted in the database table 'images' and then uploaded to the _uploads/name_of_the_album/ directory.
The problem is, when I choose some images and hit upload, only the first image is uploaded correctly, the other images fail.
Here is my code:
if(isset($_FILES['image']) === true){
$files = $_FILES['image'];
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$album_id = (int)$_GET['album_id'];
$album_name = $_GET['album_name'];
for($i=0; $i<count($files['name']); $i++){
$name = $files['name'][$i];
$tmp_name = $files['tmp_name'][$i];
$size = $files['size'][$i];
$ext = explode('.', $files['name'][$i]);
$ext = strtolower(end($ext));
$img_name = explode('.', $files['name'][$i]);
$img_name = strtolower(current($img_name));
//do some testing echos to see the result
//echo $img_name."<br>";
//here i'm going to add some validation as soon as
// i fix the multi-upload problem
//insert image into database
$query_insert_image = "INSERT INTO `images` (album_id, image_name, image_ext) VALUES ({$album_id}, '{$img_name}', '{$ext}') ";
$insert_image = mysql_query($query_insert_image, $connection) or die(mysql_error());
if(mysql_affected_rows() == 1){
move_uploaded_file($tmp_name, '../_uploads/'.$album_name.'/'.$name);
}
//redirect
redirect_to("view_album.php?succeed=1");
}//end the for loop
//echo '<pre>',print_r($files, true),'</pre>';
}
And here is some of the code of the form:
<form action="" method="post" enctype="multipart/form-data" name="formUploadImages" id="formUploadImages">
<p>
<label for="image">Choose one or more Image(s):</label><br />
<input type="file" name="image[]" id="image" /><br />
<input type="file" name="image[]" id="image" /><br />
<input type="file" name="image[]" id="image" /><br />
<input type="file" name="image[]" id="image" /><br />
<input type="file" name="image[]" id="image" />
</p>
......
Any ideas what I'm doing wrong?
I think you're cutting the branch from under your own feet.
redirect_to("view_album.php?succeed=1");
Redirecting means refreshing the page which means the end of execution. When that redirect is triggered after the first for loop ends and first image is uploaded the for will not continue to the next iteration.
And the fix of course is to push that line after the for loop (and never expect anything after a redirect to ever execute - unless the headers are already sent).
Most functions that do what redirect_to() does (it's not a core function it's based on another function header()) also make sure execution stops (have a line calling header() and another line calling die()/exit()).
try this php code ,working for me:
for($i=1;$i<6;$i++)
{
if(!empty($_FILES['image_upload'.$i])):
$target = "images/".$_FILES['image_upload'.$i]['name'];
$image_upload.= ",".mysql_real_escape_string(($_FILES['image_upload'.$i]['name']));
move_uploaded_file($_FILES['image_upload'.$i]['tmp_name'], $target);
endif;
}
create a folder in your root named "images" ,all the images will be moved in this folder.
html form may be looks like:
<form action="" method="post" enctype="multipart/form-data" name="formUploadImages" id="formUploadImages">
<p>
<label for="image">Choose one or more Image(s):</label><br />
<input type="file" name="image_upload1" id="image_upload1" /><br />
<input type="file" name="image_upload2" id="image_upload2" /><br />
<input type="file" name="image_upload3" id="image_upload3" /><br />
<input type="file" name="image_upload4" id="image_upload4" /><br />
<input type="file" name="image_upload5" id="image_upload5" />
</p>
......
this code is running on my end ,and after some editing as according to your needs may be useful for you.
Happy coding!
foreach($_POST['image'] as $report_id){
$sql="INSERT INTO images (album_id, image_name, image_ext) VALUES ('{$album_id}', '{$report_id}', '{$ext}') ";
$queryExe=mysql_query($sql);
}
replace this code in the place of your code after "//insert image into database" .
http://php.net/manual/en/features.file-upload.multiple.php
Read the Warning block 'Since PHP 5.2.12, the max_file_uploads configuration...'. Maybe that's the problem.
And there are some good examples and maybe You should use foreach instead of for.
1) Create a .htaccess file in the root folder of web server.
2) Put the following code in side the .htaccess file and save it.
php_value upload_max_filesize 20M
php_value post_max_size 20M
php_value max_execution_time 200
php_value max_input_time 200
Now you can upload the file-size up-to 20MB in a simple way using file field in your html form and move_uploaded_file() function available in PHP.

Upload to a PHP Server, using Ajax ( XMLHttp POST)

Right now i'm using the below method to Upload a file to PHP
<form enctype="multipart/form-data" action="http://sserver.com/fileupload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="30000000" />
<input type="hidden" name="filename" value="file_uploaded.gif" />
<input type="hidden" name="username" value="foobar"/>
Please choose a file:
<input name="uploaded" type="file" /><br />
<input type="submit" value="Upload" />
</form>
I read the $_POST and $_FILE in php to complete upload like this.
$target = $_SERVER['DOCUMENT_ROOT']."/test/upload/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
echo $target;
$ok=1;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploaded']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
My questions is , can i change the above said code (HTML) to an Ajax XMLHttpRequest without changes in PHP.
You cannot send files to the server via AJAX alone. This is because Javascript (when run in a browser) does not have access to the host's file system.
There are ways to make AJAX-style upload boxes using iframes, where the whole page is not reloaded during an upload, but this is not a simple task in itself. jQuery provides a couple of libraries to make this easier.
EDIT As ThiefMaster rightly points out HTML5 provides mechanisms for doing this more neatly.

error uploading file via php

I am using this script to upload files. I am not perfoming any check on filetype since its the first time I am trying. I am using Ubuntu and in php.ini file file upload is set to 'on'. But still I am not able to upload file.
<?php
if(isset($_POST['send']))
{
$uploaddir = "/home/harbhag/Desktop/";
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo $uploadfile;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
}
?>
<html>
<form enctype="multipart/form-data" action="upload.php" method="POST">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="30000000" />
<!-- Name of input element determines name in $_FILES array -->
Send this file: <input name="userfile" type="file" />
<input type="hidden" name="send" value="send" />
<input type="submit" value="Send File" />
</form>
</html>
You should use $uploaddire and $uploadfile both variables to make a valid path for file.
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploaddir.$uploadfile)) {
And also note the points
Destination directory should have write permissions
Size of File to be uploaded must meet php's upload_max_filesize (default value is 2MB )limit
Be extra careful when using move_uploaded_file. It will not move files between partitios, and hostng companies may have their upload temp directory elsewhere tha your php files.
It's a safer choice to use:
$tempname = $_FILES['userfile']['tmp_name'];
if (is_uploaded_file($tempname)) {
copy($tempname, $uploadfile);
}

Categories