Responsive File Manager upload issues - php

I've been running the Responsive File Manager recently, both on my local machine as well as a hosted server and have received different issues for each, despite the code being the same. These issues are all related to the uploading of files - currently the tested files have all been only JPEG files, where JPEG files larger than 2 MB are not able to be uploaded.
Shared issues:
For both local machine & hosted server, if the uploaded image exceeds 8MB, then I receive the following error message:
The uploaded file exceeds the max size allowed
Local machine issues:
For the local machine only, if the uploaded image is greater than 2MB but less than 8MB, I receive the following error message:
Warning: mime_content_type(): Empty filename or path in C:\xampp\htdocs\project\webroot\3rdparty\responsive file manager\filemanager\upload.php on line 92
where line 92 refers to this specific line within a set of if statements:
if ( ! empty($_FILES) || isset($_POST['url']))
{
if(isset($_POST['url'])){
$temp = tempnam('/tmp','RF');
$handle = fopen($temp, "w");
fwrite($handle, file_get_contents($_POST['url']));
fclose($handle);
$_FILES['file']= array(
'name' => basename($_POST['url']),
'tmp_name' => $temp,
'size' => filesize($temp),
'type' => explode(".", strtolower($temp))
);
}
$info = pathinfo($_FILES['file']['name']);
$mime_type = $_FILES['file']['type'];
if (function_exists('mime_content_type')){
$mime_type = mime_content_type($_FILES['file']['tmp_name']); //line 92
}
}
I also receive this error as well:
File extension is not allowed. (#C:\xampp\htdocs\project\webroot\3rdparty\responsive file manager\filemanager\upload.php#260)
which refers to this set of if statements:
if ( ! empty($_FILES) || isset($_POST['url']))
{
else // file ext. is not in the allowed list
{
response(trans("Error_extension").AddErrorLocation(), 406)->send(); //line 260
exit();
}
}
Server issues:
On the server, those two issues are replaced by this single error:
Not enough Memory
(#/home/site/public_html/webroot/3rdparty/responsive file manager/filemanager.upload.php#241)
which refers to this set of if statements:
if ( ! empty($_FILES) || isset($_POST['url']))
{
if (in_array(fix_strtolower($extension), $ext))
{
if ($is_img)
{
$memory_error = FALSE;
if ( $extension != 'svg' && !create_img($targetFile, $targetFileThumb, 122, 91))
{
$memory_error = TRUE;
}
// not enough memory
if ($memory_error)
{
unlink($targetFile);
response(trans("Not enought Memory").AddErrorLocation(), 406)->send(); //line 241
exit();
}
}
}
}
Attempts so far:
I've looked at the following:
With the file extensions issue on my local machine, I checked the allowed file extensions in the config.php file, but both formats of jpeg were already there:
'ext_img' => array( 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'svg' ), //Images
Meanwhile in include\mime_type_lib.php, both formats of jpeg were already there:
$mime_types = array(
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
)
On my local machine, I increased the upload_max_filesize to 128M. Meanwhile on the server, I used cPanel's PHP settings to do the same thing. Additionally in the config.php file, I changed the MaxSizeUpload setting to match the above changes as follows:
'MaxSizeUpload' => 128,
I did also check against the latest version of config.php and upload.php to see if my versions were outdated, but that wasn't the case.

Try this:
if ( ! empty($_FILES) || isset($_POST['url']))
{
if(isset($_POST['url'])){
if(FALSE === ($temp = tempnam('/tmp','RF'))){
response(trans("Failed to create temporary file").AddErrorLocation(), 406)->send();
exit();
}
$handle = fopen($temp, "w");
fwrite($handle, file_get_contents($_POST['url']));
fclose($handle);
$explUrl = explode(".", basename($_POST['url']));
$suffix = array_pop($explUrl);
$_FILES['file']= array(
'name' => basename($_POST['url']),
'tmp_name' => $temp,
'size' => filesize($temp),
// type should be mime-type not file suffix
'type' => $suffix,
'error' => UPLOAD_ERR_OK
);
}
if($_FILES['file']['error'] !== UPLOAD_ERR_OK){
response(trans("Error upload code: ".$_FILES['file']['error']).AddErrorLocation(), 406)->send();
// error code list: http://php.net/manual/en/features.file-upload.errors.php
exit();
}
if(empty($_FILES['file']['tmp_name'])){
response(trans("Error upload").AddErrorLocation(), 406)->send();
exit();
}
$info = pathinfo($_FILES['file']['name']);
$mime_type = $_FILES['file']['type'];
if (function_exists('mime_content_type')){
$mime_type = mime_content_type($_FILES['file']['tmp_name']);
}
}

Related

Files with specific extensions are not getting attached

I'm creating a form where I've a place for attaching files. But, files with specific extensions like .xls, .sql etc., are not getting attached. But, other files like .docx, .pdf etc., are getting attached. This is how I tried:
function file_upload($control_id, $target_directory) {
if(isset_file($control_id)) {
if(file_exists($target_directory) == false) {
mkdir($target_directory, 0777, true); //to be create the directory recursively
}
$file_name = basename($_FILES[$control_id]["name"]); //to be get file name
write_log($file_name);
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION); //to be get file extension
write_log($file_extension);
$file_size = $_FILES[$control_id]["size"]; //to be get file size in bytes
write_log($file_size);
$target_file_name = round(microtime(true) * 1000).".".$file_extension; //to be get target file name
$target_file_path = $target_directory.$target_file_name; //to be get target file
if(file_exists($target_file_path) == true) {
chmod($target_file_path, 0755); //Change the file permissions if allowed
unlink($target_file_path); //remove the file
}
if (move_uploaded_file($_FILES[$control_id]["tmp_name"], $target_file_path) == true) {
$arr = array(
"status" => true,
"message" => "The file ".$file_name." has been uploaded.",
"file_name" => $file_name,
"file_extension" => $file_extension,
"file_size" => $file_size,
"uploaded_file_name" => $target_file_name,
"uploaded_file_path" => $target_file_path
);
} else {
$arr = array(
"status" => false,
"message" => "Sorry, there was an error uploading your file."
);
}
} else {
$arr = array(
"status" => false,
"message" => "Please select file"
);
}
//echo json_encode($arr);
return $arr;
}
$id = intval(mysqli_real_escape_string($mysqli, $_REQUEST["id"]));
$upload_directory = "uploads/attachments/";
$result = file_upload("contract_attachment", "../".$upload_directory);
if($result[status] == true) {
$query = "insert into `attachments`
(
`id`,
`file_name`,
`file_extension`,
`file_size`,
`uploaded_file_name`,
`uploaded_file_path`
)
values
(
'id',
'".addslashes($result['file_name'])."',
'".$result[file_extension]."',
'".$result[file_size]."',
'".$result[uploaded_file_name]."',
'".$upload_directory.$result[uploaded_file_name]."'
)";
mysqli_query($mysqli, $query) or throwexception(mysqli_error($mysqli));
}
echo json_encode(array("message" => "Record submitted successfully"));
exit;
The problem is, when ever I try to attach a file with extension .xls or .sql, the $file_name, $file_extension, $file_size will get a value. For example, if the file I'm attaching is format.xls, it showed $file_name = format, $file_extension = .xls and $file_size = 0. Since the file size it's taking is zero, the condition "$result[status]" fails. So, the file is not getting attached.
If I attach files like .pdf or .docx I get the correct values. For example, if I attach file like format.pdf, it showed $file_name = format, $file_extension = .pdf, $file_size = 9824. And the file is also getting attached.
But, I don't know what's wrong with this code, since files with extensions .xls and .sql are not getting attached. Can someone correct this and tell whats wrong with this?

PHP upload file not working right

I have this script that is uploading file to directory and form data to database. But some how the file is not uploading and says the
variable '$filedestination' is undefined.
if(!isset($error)){
try{
if(isset($_FILES['cv'])){
$file = $_FILES['cv'];
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array('pdf', 'doc');
$cl_name = e($_POST['cl_name']);
if(in_array($file_ext, $allowed)){
if($file_error === 0){
$new_file_name = 'cv-'.$cl_name.'-'.$file_ext;
$file_destination = 'cv/' . $new_file_name;
if(move_uploaded_file($file_tmp, $file_destination)){
} else{
$error[] = 'No se podido subir el c.v.';
}
}else{
$error[] = 'Problema';
}
}
}
$handler = $db->prepare('INSERT INTO work_with_us (work_area, cl_name, cl_last_name, cl_dir, cl_city, cl_provincia, cl_tel, cl_email, work_comentario, is_cv, cv_url) VALUES (:work_area, :cl_name, :cl_last_name, :cl_dir, :cl_city, :cl_provincia, :cl_tel, :cl_email, :work_com, :is_cv, :cv_url)');
$handler->execute(array(
':work_area' => e($_POST['work_area']),
':cl_name' => e($_POST['cl_name']),
':cl_last_name' => e($_POST['cl_last_name']),
':cl_dir' => e($_POST['cl_dir']),
':cl_city' => e($_POST['cl_city']),
':cl_provincia' => e($_POST['cl_provincia']),
':cl_tel' => (int)$_POST['cl_tel'],
':cl_email' => e($_POST['cl_email']),
':work_com' => e($_POST['work_comentario']),
':is_cv' => 'Si',
':cv_url' => $file_destination
));
}catch(PDOException $e){
$error[] = $e->getMessage();
}
}
Thing is i have the same script used, in other file and for uploading pictures and it works fine but this one for .pdf and .doc its somehow not working.
You are only allowing pdf and doc :
$allowed = array('pdf', 'doc');
So png is not allowed. As for the word file, make sure you are uploading a .doc file and not a .docx since it will not be allowed. You can add a list of allowed extensions that covers all Microsoft word extensions.
As for Microsoft extensions, check this link.
just define your $filedestination variable globally means out of if block. Your Code is OK.
Give R/W permission to the folder in which you want to move/upload your file.
Actually due to R/W permission your file is not moving try Chmod command for giving R/W permission ; if you are working on linux.
Kindly check if there is any content in $error or check $error variable value...
my another suggestion is rather than to check $file['error'],
check (getimagesize($_FILES["fileToUpload"]["tmp_name"]!==false)
Please make sure that a folder named 'cv' exists in your localserver.
And, I just noticed in your code:
$new_file_name = 'cv-'.$cl_name.'-'.$file_ext;
You will have an output like this: myfile-doc
When it is supposed to be: myfile.doc
So, I suppose it should be:
$new_file_name = 'cv-'.$cl_name.'.'.$file_ext;
I do not know if this could help you but I just notice it.

Superglobal $_FILES array error element

In the $_FILES array how do you determine what the [error] element means?
It is outputting a 1, which means that it encounters an error, but how can I figure out what error this is, specifically so I can deal with it?
Otherwise I am stuck and the [error] = 1 is kind of useless since it doesn't give me much information about how to remedy the situation.
(basically is there any way to extract more information out of the error array element other then the 1 value that indicates there is an error). If there is no such way to figure out what [error] is, what is another way of figuring out why my file is not uploading properly?
This is what I have tried:
<?php
if(isset($_FILES['file'])) {
$file = $_FILES['file'];
//File properties
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
//Work out the file extension
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array('txt', 'jpg', 'mp3', 'mpeg3', 'mpeg', 'mpeg-3', 'zip');
if(in_array($file_ext, $allowed)){
if($file_error == 0){
if($file_size <= 10000000){
$file_name_new = uniqid('', true) . '.' . $file_ext;
$file_destination = 'uploads/' . $file_name_new;
if(move_uploaded_file($file_tmp, $file_destination)){
echo $file_destination;
}
}
}
else{
echo $file_error;
}
}
}
?>
<!doctype html>
<html>
<body>
<br><br>
Click <a href='./member.php'>here</a> to go back to the member page
<br><br>
<?php
if(isset($_POST['upload'])) {
echo "<pre>";
print_r($_FILES);
echo "</pre>";
}
?>
</body>
</html>
this is what it outputs for mp3 files:
1
Click here to go back to the member page
Array
(
[file] => Array
(
[name] => soundfile.mp3
[type] =>
[tmp_name] =>
[error] => 1
[size] => 0
)
)
(1) means : The uploaded file exceeds the upload max filesize. which is 2M and I'm sure your mp3 file size is bigger than that.
To change this directive you have two options :
1 - From php.ini (if you don't know where it is, use phpinfo() function), and change upload_max_filesize = 16M, and restart your server.
2 -From your htaccess file : php_value upload_max_filesize 16M

move_uploaded_file returns TRUE but no file in GCS

Very new to this and have been trying to get it to work.
I have a bucket called app. I have followed the instructions to give my app permissions to the GCS (https://developers.google.com/appengine/docs/python/googlestorage/index#Prerequisites). It seems to be setup correctly.
I followed How do I upload images to the Google Cloud Storage from PHP form? which has worked for others. I haven't really diverted from it.
I get move_uploaded_file returning TRUE, but no file in GCS.
The output is "MoveResult did succeed".
Anyone see anything I am doing wrong. Am I missing some setup code or something?
Here is the code:
if(!is_uploaded_file($_FILES['file']['tmp_name'])) {
$profile_pic_path='default';
}
else { //file exists
$gs_name = $_FILES["file"]["tmp_name"];
$fileType = $_FILES["file"]["type"];
$fileSize = $_FILES["file"]["size"];
$fileErrorMsg = $_FILES["file"]["error"];
$fileExt = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
// change name if you want
$fileName = 'profile_pic.jpg';
// put to cloud storage
$image = file_get_contents($gs_name);
$options = [ "gs" => [ "Content-Type" => "image/jpeg"]];
$ctx = stream_context_create($options);
//file_put_contents("gs://app/".$fileName, $gs_name, 0, $ctx);
if(!move_uploaded_file($gs_name, 'gs://app/'.$fileName)){
echo json_encode(array('success' => 0,'error_message' => "MoveResult did not succeed"));
exit;
}
else{
//Get image key in or path or what not. THIS IS THE NEXT STEP
//$profile_pic_path=<something>;
echo json_encode(array('success' => 1,'info_message' => "MoveResult did succeed"));
exit;
}
}

.mp3 Filetype Upload

I'm working on a PHP upload script which allows .mp3 file uploads amongst others. I've created an array which specifies permitted filetypes, including mp3s, and set a maximum upload limit of 500MB:
// define a constant for the maximum upload size
define ('MAX_FILE_SIZE', 5120000);
// create an array of permitted MIME types
$permitted = array('application/msword', 'application/pdf', 'text/plain', 'text/rtf', 'image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/tiff', 'application/zip', 'audio/mpeg', 'audio/mpeg3', 'audio/x-mpeg-3', 'video/mpeg', 'video/mp4', 'video/quicktime', 'video/x-ms-wmv', 'application/x-rar-compressed');
So far in testing all specified filetypes have been successfully uploaded but for some reason it comes up with an error for .mp3. As you can see above I've included audio/mpeg, audio/mpeg3, and audio/x-mpeg-3 but none of them seem to make a difference.
Can someone suggest what the problem could be and also indicate which audio type is the one needed to allow .mp3 uploads?
Thanks
Update: The code I'm using to run the check on the file is as follows:
// check that file is within the permitted size
if ($_FILES['file-upload']['size'][$number] > 0 || $_FILES['file-upload']['size'][$number] <= MAX_FILE_SIZE) {
$sizeOK = true;
}
// check that file is of an permitted MIME type
foreach ($permitted as $type) {
if ($type == $_FILES['file-upload']['type'][$number]) {
$typeOK = true;
break;
}
}
if ($sizeOK && $typeOK) {
switch($_FILES['file-upload']['error'][$number]) {
case 0:
// check if a file of the same name has been uploaded
if (!file_exists(UPLOAD_DIR.$file)) {
// move the file to the upload folder and rename it
$success = move_uploaded_file($_FILES['file-upload']['tmp_name'][$number], UPLOAD_DIR.$file);
}
else {
// strip the extension off the upload filename
$filetypes = array('/\.doc$/', '/\.pdf$/', '/\.txt$/', '/\.rtf$/', '/\.gif$/', '/\.jpg$/', '/\.jpeg$/', '/\.png$/', '/\.tiff$/', '/\.mpeg$/', '/\.mpg$/', '/\.mp4$/', '/\.mov$/', '/\.wmv$/', '/\.zip$/', '/\.rar$/', '/\.mp3$/');
$name = preg_replace($filetypes, '', $file);
// get the position of the final period in the filename
$period = strrpos($file, '.');
// use substr() to get the filename extension
// it starts one character after the period
$filenameExtension = substr($file, $period+1);
// get the next filename
$newName = getNextFilename(UPLOAD_DIR, $name, $filenameExtension);
$success = move_uploaded_file($_FILES['file-upload']['tmp_name'][$number], UPLOAD_DIR.$newName);
}
if ($success) {
$result[] = "$file uploaded successfully";
}
else {
$result[] = "Error uploading $file. Please try again.";
}
break;
case 3:
$result[] = "Error uploading $file. Please try again.";
default:
$result[] = "System error uploading $file. Contact webmaster.";
}
}
elseif ($_FILES['file-upload']['error'][$number] == 4) {
$result[] = 'No file selected';
}
else {
$result[] = "$file cannot be uploaded. Maximum size: $max. Acceptable file types: doc, pdf, txt, rtf, gif, jpg, png, tiff, mpeg, mpg, mp3, mp4, mov, wmv, zip, rar.";
}
I'm getting the bottom else result telling me either the file size is wrong or the extension isn't allowed.
Update 2:
I've run a print_r of the _FILES array to hopefully provide a little more info. The results are:
Array
(
[file-upload] => Array
(
[name] => Array
(
[0] => Mozart.mp3
[1] =>
[2] =>
)
[type] => Array
(
[0] => audio/mpg
[1] =>
[2] =>
)
[tmp_name] => Array
(
[0] => /Applications/MAMP/tmp/php/phpgBtlBy
[1] =>
[2] =>
)
[error] => Array
(
[0] => 0
[1] => 4
[2] => 4
)
[size] => Array
(
[0] => 75050
[1] => 0
[2] => 0
)
)
)
MAX_FILE_SIZE is a value in Bytes
5120000 is not 500 MB. It's 5MB by my reckoning.
You'll also need to check that you're not exceeding the "post_max_size" and "upload_max_size" variables in your php.ini file
Secondly, an mp3 can be any of the following mimetypes
audio/mpeg
audio/x-mpeg
audio/mp3
audio/x-mp3
audio/mpeg3
audio/x-mpeg3
audio/mpg
audio/x-mpg
audio/x-mpegaudio
http://filext.com/file-extension/MP3
You should never assume the value in $_FILES[...]['type'] actually matches the type of the file. The client can send any arbitrary string, and it's not checked at all by PHP. See here.
You'll have to do the work yourself to actually determine what type of file was uploaded, unless you have a good reason not to care about security at all (which you probably don't). PHP provides the fileinfo package by default, which does the heavy lifting for you. See finfo_file().
why not use in_array rather than the foreach loop for type check?
when you upload a valid file, have you tried checking the values of the $sizeOK & $typeOK
I doubt if you still need this but am sure many will also be facing this same problem. This is what I did and it worked for me.
Php Code:
if(isset($_POST['submit'])) {
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
if ($fileType != 'audio/mpeg' && $fileType != 'audio/mpeg3' && $fileType != 'audio/mp3' && $fileType != 'audio/x-mpeg' && $fileType != 'audio/x-mp3' && $fileType != 'audio/x-mpeg3' && $fileType != 'audio/x-mpg' && $fileType != 'audio/x-mpegaudio' && $fileType != 'audio/x-mpeg-3') {
echo('<script>alert("Error! You file is not an mp3 file. Thank You.")</script>');
} else if ($fileSize > '10485760') {
echo('<script>alert("File should not be more than 10mb")</script>');
} else if ($rep == 'Say something about your post...') {
$rep == '';
} else {
// get the file extension first
$ext = substr(strrchr($fileName, "."), 1);
// make the random file name
$randName = md5(rand() * time());
// and now we have the unique file name for the upload file
$filePath = $uploadDir . $randName . '.' . $ext;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc()) {
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$sql = "INSERT INTO media SET
path = '$filePath',
size = '$fileSize',
ftype = '$fileType',
fname = '$fileName'";
if (mysql_query($sql)) {
echo('');
} else {
echo('<p style="color: #ff0000;">Error adding audio: ' . mysql_error() . '</p><br />');
}
and your html code will be;
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data"">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input type="file" class="file_input" name="userfile" />
<input type="submit" value="" name="submit" id="submitStatus" class="submit" />
</form>
The 5MB limit is probably your problem.
Here is some code that will give you some symbolic meaning to your errors:
class UploadException extends Exception {
public function __construct($code) {
$message = $this->codeToMessage($code);
parent::__construct($message, $code);
}
private function codeToMessage($code) {
switch ($code) {
case UPLOAD_ERR_INI_SIZE:
$message = "The uploaded file exceeds the upload_max_filesize directive in php.ini";
break;
case UPLOAD_ERR_FORM_SIZE:
$message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
break;
case UPLOAD_ERR_PARTIAL:
$message = "The uploaded file was only partially uploaded";
break;
case UPLOAD_ERR_NO_FILE:
$message = "No file was uploaded";
break;
case UPLOAD_ERR_NO_TMP_DIR:
$message = "Missing a temporary folder";
break;
case UPLOAD_ERR_CANT_WRITE:
$message = "Failed to write file to disk";
break;
case UPLOAD_ERR_EXTENSION:
$message = "File upload stopped by extension";
break;
default:
$message = "Unknown upload error";
break;
}
return $message;
}
}
// Use
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
//uploading successfully done
} else {
throw new UploadException($_FILES['file']['error']);
}
If you're getting an error from your last else statement, it is difficult to tell what exactly triggered it. Try using something like the above.
http://www.php.net/manual/en/features.file-upload.errors.php

Categories