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
Related
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']);
}
}
I am attempting to upload a image file via php and it is not working:
<?php
$target_dir = "/home/NAME/uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
move_uploaded_file($_FILES['fileToUpload']['name'], $target_dir);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
print_r($_FILES);
?>
This is what is returned, but no file actually uploads. Anyone know what is going on? Thanks
Array ( [fileToUpload] => Array ( [name] => followers.png [type] => image/png [tmp_name] => /tmp/phpKsuz1B [error] => 0 [size] => 127008 ) )
Change:
move_uploaded_file($_FILES['fileToUpload']['name'], $target_dir);
To:
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)
Change move_uploaded_file($_FILES['fileToUpload']['name'], $target_dir); to move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_dir);
move_uploaded_file needs the temporary file name in order for it to upload, not the original name of the file, since it needs a resource to move.
The uploaded file is actually $_FILES['fileToUpload']['tmp_name'], this is the file you need to move.
A good way to go about this is:
$tempFile = $_FILES['fileToUpload']['tmp_name'];
$destFile = '/dest/directory/' . $_FILES['fileToUpload']['name'];
// You'll now have your temp file in destination directory, with the original image's name
move_uploaded_file($tempFile, $destFile);
A good practice is to keep your file names unique, because you never know when different images may be named image01.jpg (more often than one would hope).
$tempFile = $_FILES['fileToUpload']['tmp_name'];
$destDir = '/dest/directory/';
$destName = uniqid() . '_' . $_FILES['fileToUpload']['name'];
$destFile = $destDir . $destName;
// Temp file is now in destination directory, with a unique filename
move_uploaded_file($tempFile, $destFile);
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.
I get the following error when trying to upload a .JPG file.
Warning: getimagesize() [function.getimagesize]: Filename cannot be empty in H:\Programs\webserver\root\media\images\upload.php on line 43
The following is part of the upload.php file:
if(isset($_FILES['files']))
{
$cat = $_POST['cat'];
$title = $_POST['title'];
$album = $_POST['album'];
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name)
{
// get dimensions of uploaded images
echo $temp = $_FILES['files']['tmp_name'][$key]; //location of file
echo $type = $_FILES['files']['type'][$key]; //image type
echo $size = $_FILES['files']['size'][$key]; // image size
>> line 43 >>**echo $size2 = getimagesize($temp); //function to get info of file and put into array**
echo $width = $size2[0]; // first part of the array is the image width
echo $height = $size2[1]; // second part fo the array is the image width
if($type == 'image/jpeg')
{
$filetype = '.jpeg';
}else{
$filetype = str_replace('image/','',$type);
}
$random_name = rand(1000,9999).rand(1000,9999).rand(1000,9999).rand(1000,9999);
$path = 'img/'.$random_name . $_FILES['files']['name'][$key];
$thumb_path = 'img/thumb_/'.$random_name .$_FILES['files']['name'][$key];
I have another .jpg image file that I have been uploading to test which uploads fine, also .png and .gif files also upload fine.
Just to add that I tried a couple more image files of a similar size and received the same error.
The first Image file was 4.2MB the second was 5MB. Why would the file size stop it uploading?
Also when using $_FILES['files']['error'][$key]; - it returns 1.
This is what i get when using print_r:
Array ( [files] => Array ( [name] => Array ( [0] => DSCN0354.JPG ) [type] => Array ( [0] => ) [tmp_name] => Array ( [0] => ) [error] => Array ( [0] => 1 ) [size] => Array ( [0] => 0 ) ) )
Lets look at the knowns:
You can upload .jpg, .gif, .png no problem
You are having problem uploading a specific .jpg image
These knowns lead me to believe that the problem image is too big for the current allowed upload_max_filesize in your php.ini settings:
$ -> php -i | fgrep -i size
upload_max_filesize => 2M => 2M
Try increasing the size to 6M or 8M and your bigger image should work.
If you add some error handling, you can easily see what the problem is using the error code:
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name)
{
if ($_FILES['files']['error'][$key] == UPLOAD_ERR_OK)
{
// good
}
else
{
// not good, see messages on http://www.php.net/manual/en/features.file-upload.errors.php
}
}
You have to check for $_FILES['error'][$key] before accessing tmp_name - the file was not uploaded, either because it is too big or some other reason (you will find out by the value of 'error' field)
Also when using $_FILES['files']['error'][$key]; - it returns 1.
Error 1: The uploaded file exceeds the upload_max_filesize directive in php.ini.
(see http://www.php.net/manual/en/features.file-upload.errors.php)
The error message states that the filename supplied is empty.
You are using:
$size2 = getimagesize($temp);
Where do you get $temp from? Is it the foreach() and if it is, you should use $tmp_name instead.
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