We are currently trying to use the extension eajaxupload for Yii but it seems to be outputting failed everytime we try to upload a file.
We have tried
a) editing the file / minimum file sizes
b) playing around with the file path (may still be incorrect, if anyone knows what the path for locally using in xampp would be, let us know. Our uploads folder is in the root of the project.)
c) changing the htiaccess php file
d) permissions
we just don't know if the code itself is appearing wrong.
controller
/* UPLOADER */
public function actionUpload(){
Yii::import("ext.EAjaxUpload.qqFileUploader");
// $folder = '/uploads/';
// $folder=Yii::getPathOfAlias() .'/upload/';
$folder=Yii::app()->baseUrl . '/uploads/';
$allowedExtensions = array("jpg","png");//array("jpg","jpeg","gif","exe","mov" and etc...
$sizeLimit = 10 * 1024 * 1024;// maximum file size in bytes
$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
$result = $uploader->handleUpload($folder);
// $return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
//
// $fileSize=filesize($folder.$result['filename']);//GETTING FILE SIZE
// $fileName=$result['filename'];//GETTING FILE NAME
//
// echo $return;// it's array
$result = $uploader->handleUpload($folder);
$fileSize=filesize($folder.$result['filename']);//GETTING FILE SIZE
$fileName=$result['filename'];//GETTING FILE NAME
$result=htmlspecialchars(json_encode($result), ENT_NOQUOTES);
echo $result;// it's array
}
View
*$this->widget('ext.EAjaxUpload.EAjaxUpload',
array(
'id'=>'uploadFile',
'config'=>array(
'action'=>'/upload/',
// 'action'=>Yii::app()->createUrl('controllers/uploads/'),
'allowedExtensions'=>array("jpg","png"),//array("jpg","jpeg","gif","exe","mov" and etc...
'sizeLimit'=>10*1024*1024,// maximum file size in bytes
//'minSizeLimit'=>10*1024*1024,// minimum file size in bytes
'onComplete'=>"js:function(id, fileName, responseJSON){ alert(fileName); }",
'messages'=>array(
'typeError'=>"{file} has invalid extension. Only {extensions} are allowed.",
'sizeError'=>"{file} is too large, maximum file size is {sizeLimit}.",
'minSizeError'=>"{file} is too small, minimum file size is {minSizeLimit}.",
'emptyError'=>"{file} is empty, please select files again without it.",
'onLeave'=>"The files are being uploaded, if you leave now the upload will be cancelled."
),
'showMessage'=>"js:function(message){ alert(message); }"
)*
I got the same problem long ago.
You have to make sure that:
you get the local path, not url (Yii::getPathOfAlias('webroot')).
the $sizeLimit has to be less than the php options 'post_max_size' and 'upload_max_size'. You can check their values with ini_get(variable) and convert it to Bytes.
Also noticed that you are trying to upload the file twice.
If none of them work post the error message that you are getting.
It seems to me that your action is wrong in the
'config'=>array(
'action'=>'/upload/',
If you are uploading to the public function actionUpload()
then your action must be 'upload/upload' because the ConrollerName/ActionName must match the 'action' in your widget
'config'=>array(
'action'=> Yii::app()->baseUrl . '/upload/upload',
or
'config'=>array(
'action'=>$this->createUrl('upload/upload')
Take a look at this too: http://www.yiiframework.com/doc/guide/1.1/en/topics.url
Good luck
To update this, it wouldn't work on local server Xampp on MAC.
It worked on our live dev server, but not the live server. Seems the extension is server dependant. There is a lack of documentation and I imagine there is a fix, but it answers a lot of questions how the code is fine but not working.
Related
This is the code I have:
$from = ...; // original uploaded file
$target = ...; // save path for optimized file
#unlink($target); // removes file if already exists
$image_o = imagecreatefromjpeg($from); // get a file
imagejpeg($image_o, $target, 85); // save optimized
imagedestroy($image_o); // free memory
But it doesn't do anything. This is going in loop, but now I test it on the single file. Seems to be working on smaller files. I tried image with size ~120 kB and optimized OK. But file with more than 1 MB, it will do nothing and those are files I really need to optimize. I also tried this:
set_time_limit(6000);
ini_set('memory_limit', '200M');
But no help. I'm working on a shared hosting, so I have no access to the php.ini or to install 3rd party PHP extension. Is there an alternative for imagecreatefromjpeg which seems to be the problem?
I have the following PHP code that lets me back up files to Dropbox:
// Dropbox username/password
$dropbox_email = 'xxxxxxxxxx';
$dropbox_pass = 'xxxxxxxxxxx';
include('DropboxUploader.php');
$uploader = new DropboxUploader($dropbox_email, $dropbox_pass);
$uploader->upload('backup-images.php','Backup/');
$uploader->upload($zipArchiveName,'Backup/');
File backup-images.php is around 1kb while $zipArchiveName is around 400Mb. I seem to mange to upload backup-images.php but not $zipArchiveName.
I tried using
ini_set('max_execution_time', 0);
ini_set('memory_limit', '-1');
I also tried modifying php.ini i.e. max_execution_time and the memory_limit but I can't seem to upload the huge file to dropbox. I have ample of space on my dropbox account.
In my case I donot wish to use the Dropbox SDK but DropboxUploader.php found here.
I'd like suggestions or reasons why this isn't working or ideas how to get around it.
One way you can go around this issue by splitting your backup file into multiple files. TAR archiver has a way to create multi-part archives. Take a look: https://unix.stackexchange.com/questions/21373/can-i-automate-tars-multi-volume-feature
There is a constant in that class that provides upload size limit at this line:
const DROPBOX_UPLOAD_LIMIT_IN_BYTES = 314572800;
This is 300MB. So this class should throw an Exception in the following portion of code for a 400MB file:
$filesize = filesize($source);
if ($filesize < 0 or $filesize > self::DROPBOX_UPLOAD_LIMIT_IN_BYTES) {
throw new Exception("File '$source' too large ($filesize bytes).", self::CODE_FILESIZE_TOO_LARGE);
}
Are you not seeing this this Exception in error logs?
I don't know if that is the true current limit for this Dropbox API. You may want to check their documentation to see if you can bump up the max size constant.
If this is a newby question, forgive me. I have coded a php file uploader. After hearing that hackers could attatch/disguise code to images to infect sites, I got an idea to solve that problem. To convert the upload image to another file format (png) and then to another (jpg) with 70% quality. This caused the malware to become corrupted. The problem is, this total conversion process takes a about 1 minute at top speed. The service I'm making needs to be quick to handle the file uploads so that the users can go about the work. How can I speed up this process? The upload code is below (important variables are blanked).
// upload the file
$status = "...recieving the file...";
move_uploaded_file($_FILES["file"]["tmp_name"], "$folder" . $_FILES["file"]["name"]);
$status = "...processing the file...";
// convert the file to destroy viruses
$filename21 = "$folder" . $_FILES["file"]["name"];
imagepng(imagecreatefromstring(file_get_contents($filename21)), "$folder"."debug.".$picture_newname.".png");
$imageTmp=imagecreatefrompng("$folder"."debug.".$picture_newname.".png");
imagejpeg($imageTmp, "$folder".$picture_newname.".jpg", 90);
imagedestroy($imageTmp);
These are the steps it follows:
Scan database for file with the same name
if file with same name is found, rename the current upload
receive the file
"evaluate" the file (the double conversion process to protect the server)
insert the info into the uploads database
If any other codes are needed (or if i should do some more timing) please let me know. Thanks in advance for your assistance.
This is a crazy idea. You're not just tying up the server in converting between image formats, you're also degrading the quality of every uploaded image.
I'd recommend a different approach
When a file is uploaded, use PHP's getimagesize() function to check the image. If this function returns FALSE (or an unexpected image type, or strange dimensions, etc.), then the file is corrupt and can be deleted.
Use exiftool or something similar to strip away all the metadata from the uploaded file before you store it away on the server. That way you can ensure that the file only contains image data.
Perhaps you could check that the value of $_FILES["file"]["name"] doesn't contain anything sneaky like ../../ before you use it to save the file on your server.
It's totally bad idea implement double conversion for security purpose, because of DoS attack.
Balanced solution between speed & security must contain:
Check MIME type.
Check file extension.
Check file size. (highly recommended)
Check image size. (optional, depends on application requirements)
Something like this:
$allowable_types = array(
'png' => 'image/png',
'jpeg' => 'image/jpeg',
'gif' => 'image/gif'
);
$max_file_size = 10240; // 10K limit example
$finfo = new finfo(FILEINFO_MIME_TYPE);
$type = $finfo->file($_FILES['name']['tmp_name']);
$size = filesize($_FILES['name']['tmp_name']);
$info = pathinfo($_FILES['name']['tmp_name']);
if (isset($allowable_types[$info['extension']])
and $type === $allowable_types[$info['extension']]
and $size <= $max_file_size
) {
// check image size if your app require this
move_uploaded_file($_FILES['name']['tmp_name'], $destination);
}
Update
I would not recommend to use $_FILES['file']['name'] in destination path or scan whole directory for same name. Because of some security flaws and performance drop. Better solution is to generate unique name for each image:
$new_name = uniquid() . '.' . $info['extension'];
$destination = $upload_path . $new_name;
I am trying to take a pic upload from a mobile device to a server. We are building with PhoneGap (Javascript), so we are having turn it into a string in order to send it to the server. I am having problems once I receive it, to turn it back into a readable image file.
Simply put, I need to take a string and a file name sent to me, decode it, convert it into a .png, then crop it into a circular image.
This is what I have going on currently
if (isset($_POST['file']))
{
//Result variable
$result = false;
$pic = base64_decode($_POST['file']);
$filename = $_POST['filename'];
if (strlen($pic) > 9 )
{
$fh = fopen("/var/www/pics/events/".$filename, 'w') or die("can't open file");
fwrite($fh, $pic);
fclose($fh);
}
}
I think I can get the rest of the code to work if I can figure out what I am doing wrong here that makes it not save properly as a image file? The file uploads correctly, but it stores with out an extension, and when I point to it in my browser, it comes up like it is supposed to be an image file, but never displays the image. That little broken picture icon with the colored shapes is what I get when I direct to it's location.
Do I need to be aware of what image type is being sent during this process at all? How is it knowing if it is a .gif, .jpg/jpeg, .png, etc...?
Thanks in advance for any help!
Nathan
For Security reasons you should sanitize the file name to prevent directory traversal.
On a brighter note, make sure the file is saved with the proper extension; if you are already saving with the correct extension you could have an encoding issue from the app.
If neither of the previous possibilities are the case make sure that your String Size does not exceed the maximum POST size limit in your php.ini; if that is the case increase the size limit.
I have a file (image) upload script in PHP that I use to upload and resize images... It uses a simple MIME type and size validation so only jpg images are allowed and 1MB max file size.
I recently discovered a problem. When I try tu upload a .avi file using the script, the script processes the file like its the correct MIME type and size and then just do nothing, just takes me back to the upload form without any error message. (Instead of showing a "file too big" message).
I mean, if I try to upload a .gif or .txt or something else I get an error, as expected.
If I try to upload any file bigger than 1MB I get an error, as expected.
Only when I try to upload a .avi file with more than 1MB I dont get any kind of error.....
Well, here the first par of the code:
// define a constant for the maximum upload size
define ('MAX_FILE_SIZE', 1024000);
if (array_key_exists('upload', $_POST)) {
// define constant for upload folder
define('UPLOAD_DIR', 'C:/Wamp/www/Version-1.4/posters_uploaded/');
// replace any spaces in original filename with underscores. At the same time, assign to a simpler variable
$file = str_replace(' ', '_', $_FILES['image']['name']);
// convert the maximum size to KB
$max = number_format(MAX_FILE_SIZE/1024, 1).'kb';
// create an array of permitted MIME types
$permitted = array('image/jpeg','image/pjpeg');
// begin by assuming the file is unacceptable
$sizeOK = false;
$typeOK = false;
// check that file is within the permitted size
if ($_FILES['image']['size'] > 0 && $_FILES['image']['size'] <= MAX_FILE_SIZE) {
$sizeOK = true;
}
// check that file is of a permitted MIME type
foreach ($permitted as $type) {
if ($type == $_FILES['image']['type']) {
$typeOK = true;
break;
}
}
if ($sizeOK && $typeOK) {
switch($_FILES['image']['error']) {
case 0: // ...................
I'm just modifying a build PHP code so Im no expert...
Any suggestions??
Thanks.
http://us3.php.net/manual/en/features.file-upload.common-pitfalls.php
It looks like your upload_max_filesize ini-setting is too low. This would cause no error to be displayed when you upload a very large file such as an AVI video.
The reason you're seeing the errors with text files and .jpg images is likely because the size of those files are greater than 1 MB, but below your upload_max_filesize setting in php.ini.
Try echoing the value of ini_get("max_upload_filesize") and see what the value is if you don't have access to the php.ini file directly.
As john Rasch mentioned above, any file above the php.ini max_upload_filesize will not process at all. so you'll have no chance to test the error for you. you have to assume it was not uploaded and validate it if it was.
now that I understand your scenario better I think this is what you can do:
// at the top of your script
$upload_success = FALSE;
// when successfully detected upload
$upload_success = TRUE;
// if successful upload code is never run
$display_error = "File not uploaded, may be too large a file, "
. "please upload less than 1MB"
;
print $display_error;
main point being:
You can't always detect upload files that are too big because they get cut off at a level deeper than where the scripts run.
I'd also suggest that you don't believe the mime type. Sometimes people have .png or .gif file that have been renamed to .jpg, or they could upload incorrect files intentionally. Use getimagesize to check if these are valid jpeg images.
Don't forget, when uploading files, that there are actually two directives you need to pay attention to in php.ini. One is upload_max_filesize, but the other is post_max_size. Generally, post_max_size should at least be equal to, and probably greater than, upload_max_filesize. You can't upload a file greater than post_max_size, regardless of what you set your upload_max_filesize.
An AVI file won't match the mime types you have listed in your permitted array. After doing your $sizeOK and $typeOK checks, check to see what values they hold, and how your script handles those values. That might hold the key to the behavior of your script.
Above this line:
if ($_FILES['image']['size'] > 0 && $_FILES['image']['size'] <= MAX_FILE_SIZE) {
$sizeOK = true;
}
Put this:
echo '<pre>' . printr($_FILES) . </pre>;
That will show you what is inside the FILES array, and should make this pretty simple to debug. Try uploading the AVI with the above line added to your script.
Using $_FILES['image']['type'] for checking MIME is not reliable, it's base on header of the client and can be spoofed. Take a look at fileinfo extension to check MIME base on the real contents.
Eight years later, the short answer for anyone, like me, stumbling around for the answer to checking the image MIME type with PHP before uploading:
if (exif_imagetype($file['tmp_name']) != IMAGETYPE_JPEG) {
$file['error'] = 'Your picture must be jpg.';
}
From the manual: http://php.net/manual/en/function.exif-imagetype.php