Zend File Transfer: Problem when uploading a single image - php

I cannot understand how ->isuploaded() works. I am suppose to upload six images to display on my index page. Now the problem is, in my update function, if I upload only one or two image $upload->isUploaded() returns a false value, but if I decide to update all six of them it returns a true value. How do I deal with this problem? Am i missing out something here?
Here is my zend file transfer upload
$upload = new Zend_File_Transfer();
$upload->addValidator('Count', false, array('min' =>1, 'max' => 6))
->addValidator('Size', false, array('max' => '1Mb'))
->addValidator('ImageSize', false, array('minwidth' => 50,
'maxwidth' => 1000,
'minheight' => 50,
'maxheight' => 1000));
if ($upload->isUploaded()) $hasImage = true;

By default Zend guess all uploaded files are invalid even if just one of submitted form file fields was empty.
Zend docs are suggest to override this behavior by calling isValid() method before receive().
So I'm not sure if suggest best solution, but it works for me:
$upload = new Zend_File_Transfer();
$upload->setDestination( 'some your destination' );
if( $adapter->isValid( 'your form file field name' ) ){
$adapter->receive( 'your form file field name' );
}
And so on with every file field name. Wrap in foreach if needed.

Use isValid() instead.
if ($upload->isValid()) {
// success!
} else {
// failure!
}
Once you know your upload passed the validators, then start processing the images.

Related

Maps image download error, routes are not coming in the image

I created a function in PHP that downloads a map created in google maps, I am able to download, however, the route is not coming when I am saving.
How the picture is coming:
How it should come:
Code:
function download_remote_file_with_curl($file_url, $save_to) {
$arrContextOptions = array(
"ssl" => array(
"verify_peer" => false,
"verify_peer_name" => false,
),
);
$response = file_get_contents($file_url, false, stream_context_create($arrContextOptions));
//echo $response;
//file_put_contents($save_to, $response);
$downloaded_file = fopen($save_to, 'wb');
fwrite($downloaded_file, $response);
fclose($downloaded_file);
}
$urlDownload = "https://maps.googleapis.com/maps/api/staticmap?size=1000x1000&maptype=roadmap&path=enc:zklaAbqcyJzCmF~#b#fBdAzCiEnKyQlFpCnMdH~_#nU~JlFlCNrw#oL~IcApEZxd#nQpgBhq#tRtStgA``Aty#`o#ll#pa#tNhFzMvJfG~D|Y~Hxd#rMll#`Rtb#jLjNzExWtFz`#bJvM|ItG`LdF|V`GvD|CL|JiBv]aGld#cHrk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xPoApfB~WzK|AHTdBDrO}A~RmBrXsCzZuA~NJx#bD|#dAfX`#{#nG&markers=color:green|label:A|-10.8819552,-61.95483539999998&markers=color:red|label:B|-12.457280801085,-64.2310285267651&key=yourkey";
download_remote_file_with_curl($urlDownload, realpath('C:/test') . '/' . 'test' . '.jpg');
?>
Thank you!
I don't know if what I'm about to write makes sense, but the route that you want to download is an item that appears once it's selected.
For example when the "SKIP" buttom in Youtube appears to quit an advertisement, it creates an instance of that box in HTML, and then it dissappears when Add is over.
I think that the route is this kind of instance and you must add a line of code to also take that piece of html

Laravel 5 Image Upload

I am trying to upload Images with a form. I have 5 fields in total and don't want to make all fields required. However there is an exception if I leave one of the fields blank. But everything works fine when I upload all 5 images.
I have no rules in my $rules array. Something goes wrong with isValid().
Error:
FatalErrorException in ProfilesController.php line 191:
Call to a member function getClientOriginalExtension() on a non-object.
Can somebody point me into the right direction please.
My Controller:
public function update(ProfileRequest $request, $id)
{
$profile = Profile::findOrFail($id);
$request->merge([ 'wifi' => $request->has('wifi') ? true : false,
'takeaway'=> $request->has('takeaway') ? true : false,
'ec'=> $request->has('ec') ? true : false,
'creditcard'=> $request->has('creditcard') ? true : false,
'cash'=> $request->has('cash') ? true : false,
'wheelchair'=> $request->has('wheelchair') ? true : false,
'outdoor'=> $request->has('outdoor') ? true : false,
'tv'=> $request->has('tv') ? true : false,
'service'=> $request->has('service') ? true : false,
'smoking'=> $request->has('smoking') ? true : false,
'reservation'=> $request->has('reservation') ? true : false,
'brunch'=> $request->has('brunch') ? true : false,
]);
// getting all of the post data
$file = array('image_profilehero' => Input::file('image_profilehero'),
'image_avatar' => Input::file('image_avatar'),
'pdf' => Input::file('pdf'),
'restaurantscene1' => Input::file('restaurantscene1'),
'restaurantscene2' => Input::file('restaurantscene2')
);
// setting up rules
$rules = array(//'image_profilehero' => 'required',
//'image_avatar' => 'required'
); //mimes:jpeg,bmp,png and for max size max:10000
// doing the validation, passing post data, rules and the messages
$validator = Validator::make($file, $rules);
if ($validator->fails()) {
// send back to the page with the input data and errors
return Redirect::to('backend/profile')->withInput()->withErrors($validator);
}
else {
// checking file is valid.
if (Input::file('image_profilehero') or Input::file('image_avatar')->isValid() or Input::file('pdf')->isValid() or Input::file('restaurantscene1')->isValid() or Input::file('restaurantscene2')->isValid()) {
$destinationPathAvatar = 'uploads/avatar'; // upload path Avatar
$destinationPathProfileHero = 'uploads/profilehero'; // upload path ProfileHero
$destinationPathPdf = 'uploads/speisekarten'; // upload path ProfileHero
//Restaurant Scene Bilder
$destinationPathRestaurantScene1 = 'uploads/restaurantscene'; // upload path RestaurantScene
$destinationPathRestaurantScene2 = 'uploads/restaurantscene'; // upload path RestaurantScene
$extensionAvatar = Input::file('image_avatar')->getClientOriginalExtension(); // getting image extension
$extensionProfileHero = Input::file('image_profilehero')->getClientOriginalExtension(); // getting image extension
$extensionPdf = Input::file('pdf')->getClientOriginalExtension(); // getting image extension
$extensionRestaurantScene1 = Input::file('restaurantscene1')->getClientOriginalExtension(); // getting image extension
$extensionRestaurantScene2 = Input::file('restaurantscene2')->getClientOriginalExtension(); // getting image extension
//$fileName = rand(11111,99999).'.'.$extension; // renameing image
$fileNameAvatar = '/avatar/avatar_'.Auth::user()->id.'.'.$extensionAvatar;
$fileNameProfieHero = '/profilehero/profilehero_'.Auth::user()->id.'.'.$extensionProfileHero;
$fileNamePdf = '/speisekarten/pdf_'.Auth::user()->id.'.'.$extensionPdf;
$fileNameRestaurantScene1 = '/restaurantscene/scene1_'.Auth::user()->id.'.'.$extensionRestaurantScene1;
$fileNameRestaurantScene2 = '/restaurantscene/scene2_'.Auth::user()->id.'.'.$extensionRestaurantScene2;
Input::file('image_profilehero')->move($destinationPathProfileHero, $fileNameProfieHero); // uploading file to given path
Input::file('image_avatar')->move($destinationPathAvatar, $fileNameAvatar); // uploading file to given path
Input::file('pdf')->move($destinationPathPdf, $fileNamePdf); // uploading file to given path
Input::file('restaurantscene1')->move($destinationPathRestaurantScene1, $fileNameRestaurantScene1); // uploading file to given path
Input::file('restaurantscene2')->move($destinationPathRestaurantScene2, $fileNameRestaurantScene2); // uploading file to given path
// sending back with message
return redirect('backend/profile')->with([
'flash_message_important' => false,
'flash_message' => 'All done'
]);
}
else {
// sending back with error message.
return redirect('backend/profile')->with([
'flash_message_important' => false,
'flash_message' => 'Upps. Something's wrong.'
]);
}
}
//return redirect('backend/profile');
$profile->update($request->all());
}
Your code is not accounting for an empty or missing file, it's just assuming there's a file there and attempting to move it. So you end up calling methods on a non-object, likely null. You just need to do a bit of extra work to ensure you actually have objects before you call methods on them, like this:
$pdf = Input::file('pdf');
if ($pdf) {
$extension = $pdf->getClientOriginalExtension();
$pdf->move($destinationPathPdf, $fileNamePdf);
}
This way, if there's no PDF file, the if statement will be false and will skip calling methods on it, so you avoid that kind of error. It's generally good practice to do this.

drupal 6: file upload in form not working

I'm trying to have a simple form with a file upload, but it isn;t working. when I check form_state both in the validate and in the submit callbacks, the file value is missing. also check $_FILES and there's nothing.
here is the code I'm using in _form:
$form['file'] = array(
'#type' => 'file',
'#title' => 'Photo',
);
this is what i'm doing in submit:
$validators = array();
$file = file_save_upload('file', $validators, '/sites/default/files');
file_set_status($file, FILE_STATUS_PERMANENT);
krumo ($file);
You need specify $form['#attributes'] = array('enctype' => 'multipart/form-data'); apart from your other fields to make it working. See here for details.

Zend_Form_Element_Captcha Not Working

Apparently this is a common problem but I have not been able to figure out how to get a Zend Captcha Image to show up, it will create the image and it will create the hidden element but the image tag never shows up, does anyone have a solution??
Here is the code that doesn't work:
<?php
class Application_Form_Contact extends Zend_Form
{
public function init()
{
/* Form Elements & Other Definitions Here ... */
$this->setAction('/contact/')->setMethod('post');
$element = new Zend_Form_Element_Text('name');
$element->setLabel('Name:')
->setRequired(true)
->addFilter('HtmlEntities');
$this->addElement($element);
$element = new Zend_Form_Element_Text('phone');
$element->setLabel('Phone:')
->setRequired(true)
->addFilter('HtmlEntities');
$this->addElement($element);
$element = new Zend_Form_Element_Text('email');
$element->setLabel('Email:')
->setRequired(true)
->addValidator('EmailAddress', true)
->addFilter('StripTags')
->addFilter('HtmlEntities')
->addFilter('StringToLower')
->addFilter('StringTrim');
$this->addElement($element);
$comments = $this->createElement('textarea', 'comments')
->setLabel('Comments:')
->setRequired(true)
->setOptions(array('style'=>'width:95%;'))
->addFilter('StripTags')
->addFilter('HtmlEntities')
->addFilter('StringTrim');
$this->addElement($comments);
$captcha= new Zend_Form_Element_Captcha('captcha', array(
'id'=>'captchas',
'title'=>'Security Check.',
'captcha' => array(
'captcha' => 'Image',
'required' => true,
'font'=> PUBLIC_PATH . '/verdana.ttf',
'wordlen'=>'4',
'width'=>'80',
'height'=>'50',
'ImgAlign'=>'left',
'imgdir'=> PUBLIC_PATH . '/images/captcha/',
'DotNoiseLevel'=>'0',
'LineNoiseLevel'=>'0',
'Expiration'=>'1000',
'fontsize'=>'16'
)));
$this->addElement($captcha);
$submit = new Zend_Form_Element_Submit('submit');
$submit->setLabel('Send');
$this->addElement($submit);
}
}
I've only got two ideas that might help:
Check to make sure your GD extension is enabled in php.
It requires the GD extension compiled with TrueType or Freetype support. Currently, the Zend_Captcha_Image adapter can only generate PNG images.
you may want to specify the imgUrl =>
setImgUrl($imgUrl) and getImgUrl() allow you to specify the relative path to a CAPTCHA image to use for HTML markup. The default is "/images/captcha/".
also just for information you don't need to set the element as required as the captcha is always required.
As noted, the captcha adapter itself acts as a validator for the element. Additionally, the NotEmpty validator is not used, and the element is marked as required. In most cases, you should need to do nothing else to have a captcha present in your form.
Try to edit your captcha down to bare bones
$captcha = new Zend_Form_Element_Captcha('Captcha', array(
'captcha' => array(
'captcha' => 'Image',
'wordLen' => 6,
'timeout' => 300,
'width' => 300,
'height' => 100,
'imgUrl' => '/captcha',
'imgDir' => APPLICATION_PATH . '/../public/captcha',
'font' => APPLICATION_PATH . '/../public/fonts/LiberationSansRegular.ttf')));
just get anything to work then add back what you need 'till you find the problem. I suspect you have a problem with one of your paths.
Start with the APPLICATION_PATH constant then change to PUBLIC_PATH if you feel it's better.
check your file permissions; I had to give group write access before the image would write.

Uploaded docx files turning into zip

I am currently using symfony 1.4 and would like to allow users to upload Microsoft Word docx files. Using the sfWidgetFormInputFile widget and sfValidatorFile below users are able to select and successfully upload their docx files using a simple web form.
$this->widgetSchema['file_name'] = new sfWidgetFormInputFile(array('label' => 'File'));
$this->validatorSchema['file_name'] = new sfValidatorFile(array(
'required' => true,
'path' => sfConfig::get('sf_upload_dir').DIRECTORY_SEPARATOR.sfConfig::get('app_dir_file_sharing').DIRECTORY_SEPARATOR,
'mime_types' => array('application/msword',
'application/vnd.ms-word',
'application/msword',
'application/msword; charset=binary')
), array(
'invalid' => 'Invalid file.',
'required' => 'Select a file to upload.',
'mime_types' => 'The file must be a supported type.'
));
The problem is that after the file is uploaded, the extension is changed to .zip and the file contains a file tree of xml files. My understanding is that this is because Office 2007 are now using Open xml file formats. Is there any way to prevent this from happening using symfony or PHP?
The problem is Content-Sniffing. The new Office formats ARE .zip files, and if on upload, the content is sniffed, the browser will identify this as a ZIP file and set the Content-Type header as such. Similarly, on download unless your server sets the proper Content-Type HTTP response header, the browser will assume that this is a ZIP file.
Symfony 1.3+ has an option mime_type_guessers for sfValidatorFile which allows you to define your own mime type guesser PHP callable or use a build in guesser. Calling any of the 3 built-in mime type guessers finds the correct file type for docx and keeps the the docx file extension.
Here is the updated code using guessFromFileinfo:
$this->validatorSchema['file_name'] = new sfValidatorFile(array(
'required' => true,
'path' => sfConfig::get('sf_upload_dir').DIRECTORY_SEPARATOR.sfConfig::get('app_dir_file_sharing').DIRECTORY_SEPARATOR,
'mime_type_guessers' => array('guessFromFileinfo'),
'mime_types' => array('application/msword',
'application/vnd.ms-word',
'application/msword',
'application/msword; charset=binary')
), array(
'invalid' => 'Invalid file.',
'required' => 'Select a file to upload.',
'mime_types' => 'The file must be a supported type.'
));
It seems to be a bug in Symfony's file type detection. A workaround is described.
The suggested use of mime_type_guessers uses a non-existing function.
If you want to use the sfValidatorFile method, you should write array(array('sfValidatorFile', 'guessFromFileinfo')).
The suggested solution uses no mime-type detection at all and results in problems with the classic excel format on my system.
I fixed the problem by extending the sfValidatorFile class and changing the getMimeType method.
Create a new msValidatorFile.class.php file in your lib folder :
<?php
class msValidatorFile extends sfValidatorFile
{
protected function getMimeType($file, $fallback)
{
$arrayZips = array( "application/zip",
"application/x-zip",
"application/x-zip-compressed");
$officeTypes = array(
"application/vnd.ms-word.document.macroEnabled.12",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.openxmlformats-officedocument.wordprocessingml.template",
"application/vnd.ms-powerpoint.template.macroEnabled.12",
"application/vnd.openxmlformats-officedocument.presentationml.template",
"application/vnd.ms-powerpoint.addin.macroEnabled.12",
"application/vnd.ms-powerpoint.slideshow.macroEnabled.12",
"application/vnd.openxmlformats-officedocument.presentationml.slideshow",
"application/vnd.ms-powerpoint.presentation.macroEnabled.12",
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
"application/vnd.ms-excel.addin.macroEnabled.12",
"application/vnd.ms-excel.sheet.binary.macroEnabled.12",
"application/vnd.ms-excel.sheet.macroEnabled.12",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/vnd.ms-excel.template.macroEnabled.12",
"application/vnd.openxmlformats-officedocument.spreadsheetml.template");
foreach ($this->getOption('mime_type_guessers') as $method)
{
$type = call_user_func($method, $file);
if (null !== $type && $type !== false)
{
if (in_array($type, $arrayZips) && in_array($fallback, $officeTypes))
{
return $fallback;
}
return strtolower($type);
}
}
return strtolower($fallback);
}
}
Use this new validator in your form code :
$this->validatorSchema['file'] =
new msValidatorFile(array('required' => false,
'path' => sfConfig::get('sf_upload_dir')
));

Categories