I have an HTML form as the following:
<form id="addTrack" action="/worship/script/upload.php" method="post" enctype="multipart/form-data">
<label>File:</label>
<input type="file" name="uploaded" id="addTrackFile"/>
<label>Key Title: </label>
<input type="text" name="title" id="addTrackTitle"/>
<input type="hidden" name="id" id="addTrackId"/><br>
</form>
<button onclick="uploadAddTrack()">Upload</button>
<button onclick="closeAddTrack()">Close</button>
When I submit the form the file uploads to the server properly, but when it gets redirected to the PHP action script, it gets stopped at the first error catch. The script then dumps the $_FILES variable which it returns as an empty array. As you can see in the code below, I also have it echo the error, but it also echoes an empty string.
Why am I not getting a file in the $_FILES array?
My PHP Code:
$id=$_POST["id"];
$name=$_POST["title"];
$name = str_replace(" ","",$name);
$allowed_filetypes = array('.mp3','.m4a','.wav','.wma');
$filename = $_FILES['uploaded']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
$target = "../audio/";
$target = $target . $id. "_".$name.$ext;
$ok=1;
if ($_FILES['uploaded']['error'] !== UPLOAD_ERR_OK) {
//------------This is where it gets stopped-----------------//
var_dump($_FILES);
echo $_FILES["uploaded"]["error"];
return;
}
if(!in_array($ext,$allowed_filetypes))
die("This file type is not allowed");
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
include("updateDB.php");
header("Location:/worship/cpanel/?autoload=$id");
}
The size of the file I am uploading is 9mb.
My php.ini relevant info
file_uploads: On
upload_max_filesize: 25M
upload_tmp_dir: no value
max_post_size: 8M
check you PHP.ini file. make sure the POST size is larger the 8M. because that is the default and you're sending info that is 9MB.
`; Maximum size of POST data that PHP will accept.
post_max_size = 8M`
Related
I have a form:
<form action='' enctype="multipart/form-data" method="post">
<input type="file" name="image">
<input type="submit" value="send">
</form>
I have php code:
$file = $_FILES['image']
$ext = explode(",", $file['type'])[0];
$location = "../image/movedimage.$ext";
if(move_uploaded_file($file['tmp_name'], $location)) echo 'moved';
else echo 'internal error';
This echos "moved" but the problem is that when I check the path to which the file was moved, the image file in there is corrupted.
I had to change the system of uploading the image by doing this:
$file_content = file_get_contents($file['tmp_name']);
$file_dump = file_put_contents($location, $file_content);
This attempt of placing the file directly using the file_put_contents works fine and the image file is perfect just as uploaded but using the move_uploaded_file leaves a corrupted file in the destination folder. I would like to understand why this is happening as the $file['error'] returns a value 0 and the move_uploaded_file function does not return false.
In your code by using
$ext = explode(",", $file['type'])[0];
you get the extension as image/your_image_type.
Then you are appending that with the file name, which will create an invalid image.
To get the extension, you can do as follows
$ext= explode("/", $file['type'])[1];
or
$ext = strtolower(end(explode('.',$_FILES['image']['name'])));
I want to upload the files in html as follow :
<tr><td><?php _e("Upload Trust Logo","emarksheet"); ?></td><td><label class="btn btn-danger" for="file-sel"><input id="file-sel" type="file" name="imaget" style="display:none;" size="25" />Browse to Upload Logo ....</label></td></tr>
<tr><td><?php _e("Upload Institute Logo","emarksheet"); ?></td><td><label class="btn btn-primary" for="file-sel2"><input id="file-sel2" type="file" name="image" style="display:none;" size="25" />Browse to Upload Logo ....</label></td></tr>
Two upload these files. My php code is as follow :
$path = plugin_dir_path(__FILE__);
$file = $_FILES['image'];
//print_r($_FILES);
$name1 = $file['name'];
$type = $file['type'];
$size = $file['size'];
$tmppath = $file['tmp_name'];
move_uploaded_file ($tmppath, $path.'logos/'.$name1);
//upload data end
//upload trust logo`
$file2 = $_FILES['imaget'];
//print_r($_FILES);
$name2 = $file2['name'];
$type2 = $file2['type'];
$size2 = $file2['size'];
$tmppath2 = $file2['tmp_name'];
move_uploaded_file ($tmppath2, $path.'logos/'.$name2);
When I upload the files. The file name with $name2 is uploaded but the file with name $name1 is not uploaded
Please help why it not be uploaded
As you posted, the 'image' image has an error 4 code. That means no file was uploaded, as seen here:
http://www.php.net/manual/en/features.file-upload.errors.php
Why?
Since you are getting info in $_FILES, then you are not posting a total amount of data larger than the post_max_size php.ini directive, as, in this case, $_FILE would be completelly empty.
Then, maybe the php.ini upload_max_filesize, the maximum size for a singe file, is exceeded or the max_file_uploads is set to one, as max_file_uploads is the maximum number of files allowed to be uploaded simultaneously.
Check those params at http://php.net/manual/en/ini.core.php and in your php.ini file.
I tried this snippet in my localhost server, and placed in [www_root]/tests/uploads/test1.php (note I just used the relevant part for our case):
<?php
if (empty($_FILES)) {
echo "<form enctype='multipart/form-data' method='POST' action='http://localhost/tests/uploads/test1.php'>";
echo '<input id="file-sel" type="file" name="imaget" size="25" />';
echo '<input id="file-sel2" type="file" name="image" size="25" />';
echo '<button type="submit">Submit</button>';
} else {
echo print_r($_FILES);
}
And both files where correctly uploaded. Then the problem must be in the PHP configuration, not in the actual PHP code.
My values in php.ini:
post_max_size=8M
upload_max_filesize=2M
max_file_uploads=20
This means I can upload 20 files at the same time, but they can not exceed 8M in total nor an individual file can exceed 2M.
EDIT: after modifying the php.ini file, the server must be restarted in order to get those new values loaded.
Hope it helps.
Im having problems with form validation. When I dont select a file for upload I still get an error that promts only png images valid. I thought that if no file was selected the $_FILES array would be empty.
What am I doing wrong?
my html form excerpt for file upload looks like this:
<label for="file">Filename
<span class="small">Upload image</span>
</label>
<input type="file" name="file" id="file">
my php processing looks like this:
$submitted_file = $_FILES['file'];
if(isset($submitted_file)) {
// verify the file PNG only
$fileType = exif_imagetype($submitted_file["tmp_name"]);
$allowed = array(IMAGETYPE_PNG);
$max_filesize = 512000;
if (!in_array($fileType, $allowed)) {
$proceed = false;
$arrErrors['submitted_file_ext'] = 'Please upload .png images only.';
}
}
The array that you are checking should have the field ["tmp_name"] as null if it is blank. Try this code instead:
if(!empty($submitted_file["tmp_name"])) {
The right way is to check $_FILES['error']
if ($_FILES['name']['error'] === UPLOAD_ERR_OK) {
// file successfully uploaded
}
More info here http://ru2.php.net/manual/en/features.file-upload.php
I'm trying to build a form to upload a thumbnail (image) to the server - looks like the image is successfully uploading to the servers temp folder (I've confirmed this with get_defined_vars - its giving a temp file name and no errors), but its not being moved to the folder in the DOCUMENT_ROOT
The end goal here is to get the image uploaded then return a url to be stored in MySQL
HTML Form (located in DOCUMENT_ROOT/admin)
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="thumbnail">Thumbnail </label>
<input type="file" name="thumbnail" id="thumbnail">
</form>
Upload.php
<?php
$thumbnail = uploadfile($_FILE['thumbnail']['name'],$_SERVER['DOCUMENT_ROOT'].'/thumbs/upload/',$_FILE['thumbnail']['tmp_name']);
if(($thumbnail)!== FALSE)
{echo $thumbnail;} else {echo 'upload failed<br>';}
function uploadfile($origin, $dest, $tmp_name)
{
$origin = strtolower(basename($origin));
$fulldest = $dest.$origin;
$filename = $origin;
echo '$fulldest '.$fulldest.'<br />';
echo '$filename '.$filename.'<br />';
if (move_uploaded_file($tmp_name, $fulldest))
{return $filename;}
return false;
}
?>
result (note: I've removed the actual document root)
$fulldest [DOCUMENT_ROOT] /thumbs/upload/
$filename
upload failed
I've also set an .htaccess directive for upload 500M to make sure image size isn't the problem
<IfModule mod_php4.c>
php_value upload_max_filesize 500M
php_value post_max_size 500M
</IfModule>
EDIT:: My target directory is chmod 0777 for testing - so permissions shouldn't be the problem.
I can't help noticing that your $filename is empty and $fulldest lack the filename. I think the problem is that you use $_FILE and not $_FILES.
$thumbnail = uploadfile($_FILES['thumbnail']['name'],
$_SERVER['DOCUMENT_ROOT'].'/thumbs/upload/',
$_FILES['thumbnail']['tmp_name']);
I think that would work.
I have the following code to upload a file to the server. For some weird reason, it does not work in IE and Mozilla Firefox but works perfect in Chrome. What is the problem?
PHP:
// Check post_max_size (http://us3.php.net/manual/en/features.file-upload.php#73762)
$POST_MAX_SIZE = ini_get('post_max_size');
$unit = strtoupper(substr($POST_MAX_SIZE, -1));
$multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));
if ((int)$_SERVER['CONTENT_LENGTH'] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE)
HandleError('File exceeded maximum allowed size. Your file size <b>MUST NOT</b> be more than 100kb.');
// Settings
$save_path = 'uploads/'; //getcwd() . '/uploads/';The path were we will save the file (getcwd() may not be reliable and should be tested in your environment)
$upload_name = 'userfile'; // change this accordingly
$max_file_size_in_bytes = 102400; // 100k in bytes
$whitelist = array('jpg', 'png', 'gif', 'jpeg'); // Allowed file extensions
$blacklist = array('php', 'php3', 'php4', 'phtml','exe','txt','scr','cgi','pl','shtml'); // Restrict file extensions
$valid_chars_regex = 'A-Za-z0-9_-\s ';// Characters allowed in the file name (in a Regular Expression format)
// Other variables
$MAX_FILENAME_LENGTH = 260;
$file_name = $_FILES[$upload_name]['name'];
//echo "testing-".$file_name."<br>";
//$file_name = strtolower($file_name);
////////$file_extension = end(explode('.', $file_name));
$parts = explode('.', $file_name);
$file_extension = end($parts);
$uploadErrors = array(
0=>'There is no error, the file uploaded with success',
1=>'The uploaded file exceeds the upload max filesize allowed.',
2=>'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3=>'The uploaded file was only partially uploaded',
4=>'No file was uploaded',
6=>'Missing a temporary folder'
);
// Validate the upload
if (!isset($_FILES[$upload_name]))
**HandleError('No upload found for ' . $upload_name);**//THROWS UP ERROR HERE in IE and Firefox
else if (isset($_FILES[$upload_name]['error']) && $_FILES[$upload_name]['error'] != 0)
HandleError($uploadErrors[$_FILES[$upload_name]['error']]);
else if (!isset($_FILES[$upload_name]['tmp_name']) || !#is_uploaded_file($_FILES[$upload_name]['tmp_name']))
HandleError('Upload failed.');
else if (!isset($_FILES[$upload_name]['name']))
HandleError('File has no name.');
HTML:
<form name="upload" action="/upload" method="POST" ENCTYPE="multipart/formdata">
<table border="0" cellpadding="3" cellspacing="3" class="forms">
<tr>
<tr>
<td style="height: 26px" align="center">
<font class="font_upload_picture">'.MSG142.': <input class="font_upload_picture" type="file" name="userfile">
<input type=hidden name=MAX_FILE_SIZE value=102400 />
</td>
</tr>
<tr>
<td colspan="2">
<p align="center">
<input type="image" name="upload" value="upload" src="/img/layout/btnupload.gif" border="0" />
</p>
<p> </p>
<td><img src="/img/layout/takepicture.gif" border="0" /><br> '.MSG143.'</td>
</tr>
</table>
</form>
The enctype of the form should be multipart/form-data
You have errors in your html. You're missing closing tags for a tr and td tag. Also, close off your file upload input tag />.
Some of your logic is off:
if (!isset($_FILES[$upload_name]))
will always pass. For every <input type="file"> in your form, there'll be a matching $_FILES entry, whether a file was actually uploaded or not. If no file was uploaded to being with, then you'll get error code 4.
else if (isset($_FILES[$upload_name]['error']) && $_FILES[$upload_name]['error'] != 0)
You don't have to check if the error parameter is set. as long as $upload_name has a valid file field name in it, the error section will be there. You can check for $_FILES[$upload_name], though. in case your variable's set wrong.
You've commented it out, but you're checking for valid upload types by checking the user-provided filename. Remember that the ['type'] and ['name'] parameters in $_FILES are user-supplied and can be subverted. Nothing says a malicious user can't rename bad_virus.exe to cute_puppies.jpg and get through your 'validation' check. Always determine MIME type on the server, by using something like Fileinfo. That inspects the file's actual contents, not just the filename.
So, your upload validation should look something like:
if (isset($_FILES[$upload_name]) && ($_FILES[$upload_name]['error'] === UPLOAD_ERR_OK)) {
$fi = finfo_open(FILE_INFO_MIME_TYPE);
$mime = finfo_file($fi, $_FILES[$upload_name]['tmp_name']);
if (!in_array($valid_mime_type, $mime)) {
HandleError("Invalid file type $mime");
}
etc...
} else {
HandleError($uploadErrors[$_FILES[$upload_name]['error']]);
}