zend_barcode in MVC - php

i just want an Action to print a barcode image, but i can´t get this working in MVC, i just do the following:
public function barcodeAction() {
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
Zend_Barcode::render($_GET['barcodeType'], 'image', $_GET, $_GET);
}
but when I call
/barcode?barcodeType=code39&text=ZEND-FRAMEWORK
I just obtain:
"The image couldn't be displayed because it has errors" (or something like that, browser-dependant).
Thanks!

You're likely getting an error that you can't see due to the Content-Type header that's sent by Zend_Barcode. Make sure you have log_errors turned on and a valid/writeable destination for the log configured. This way you can check the error log for anything that you normally would have read through your browser.
http://us3.php.net/manual/en/errorfunc.configuration.php#ini.log-errors

I have no problem with your code, I call this url: http://localhost/index/barcode?barcodeType=code39&text=ZEND in my browser (your code is in the IndexController) and I receive the correct image.
If I put <img src="http://localhost/index/barcode?barcodeType=code39&text=ZEND" /> in a view, I have also the image.
Mickael

I know this may be outdated now but when I had the same problem I just added
ob_clean();
in my controller so now my action looks like this
public function generateBarcodeAction() {
ob_clean();
$number = $this->params()->fromRoute('number');
$barcodeOptions = array('text' => $number);
$rendererOptions = array('imageType'=>'png');
Barcode::render(
'ean13', 'image', $barcodeOptions, $rendererOptions
);
}
and it's working like a charm

Related

Print html before downloading zip file

Hello fellow coders !
I am looking for a solution to show a html page while my php code prepares a .zip which is then downloaded. The reason is because sometimes the zips are quite bigger and take time to make.
The HTML page would be a basic "Please wait while your .zip files is being prepared".
The PHP side used is Symfony. So I come into my getInboxExportAction function by calling https://myapi.com/orders/orderid/inbox/export.
The download function (makeExportDownloadRequestResponse) works fine. But if I add a flush after making my $response, the .zip is printed to the html, instead of being downloaded...
public function getInboxExportAction(Request $request, $orderId)
{
$response = new Response($this->twig->render('base.html.twig',
['content' => '
<h1>Download</h1>
<p>Your zip is being prepared for download, please wait...</p>
']));
$response->headers->set('Content-Type', 'text/html');
//Here I would like to echo + flush my html.
//Then stop the flush and continue my code
$receivedOrder = $this->fetchRequestedReceivedOrder($orderId);
if (!$receivedOrder instanceof ReceivedOrder) {
return $receivedOrder;
}
if (!$receivedOrder->getSentorder()) {
$this->makeErrorResponse('Sent order was not found', Response::HTTP_BAD_REQUEST);
}
return $this->makeExportDownloadRequestResponse($receivedOrder->getSentorder(), $request->get('format'));
}
I am also very open to any other ideas anyone would have to fix this issue :)
Thanks,
Edit : My $this->makeExportDownloadRequestResponse() function returns a response, not a path. We unlink the file on the server for storage reasons.
$content = file_get_contents($zipTmpFile);
unlink($zipTmpFile);
$response = new Response($content);
$dispositionHeader = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT,
'myFile_' . date('Y_m_d_h_i_s') . '.zip');
$response->headers->set('Content-Disposition', $dispositionHeader);
return $response;
Second edit : I understand that what I'm trying to do (change the content-type within one call) I generally frowned upon. I'm currently trying to think of a more elegant solution.
In your getInboxExportAction, just return a response with your text.
Then, in this response, add a <meta http-equiv="refresh" content="1;url=xxx"> tag to redirect the user to another action that will generate the zip file.
You can also handle this redirection with javascript.
Note that you can use a StreamedResponse to handle the zip download: https://symfony.com/doc/current/components/http_foundation.html#streaming-a-response
The most important thing is you set $response->headers->set('Content-Type', 'text/html');, the browser will not download the .zip file.
If your makeExportDownloadRequestResponse method can return the absolute .zip file path (or you can calculate it), you can try:
public function getInboxExportAction(Request $request, $orderId)
{
$response = new Response($this->twig->render('base.html.twig',
['content' => '
<h1>Download</h1>
<p>Your zip is being prepared for download, please wait...</p>
']));
$response->headers->set('Content-Type', 'text/html');
//Here I would like to echo + flush my html.
//Then stop the flush and continue my code
$receivedOrder = $this->fetchRequestedReceivedOrder($orderId);
if (!$receivedOrder instanceof ReceivedOrder) {
return $receivedOrder;
}
if (!$receivedOrder->getSentorder()) {
$this->makeErrorResponse('Sent order was not found', Response::HTTP_BAD_REQUEST);
}
// prepare the to be downloaded zip file
// then, do sth to get the .zip file path
$zipFilePath = $this->makeExportDownloadRequestResponse($receivedOrder->getSentorder(), $request->get('format'));
// re-set header
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename=whateverName.zip');
header('Content-Length: ' . filesize($zipFilePath));
readfile($zipFilePath);
}
It will let browser downloads the zip file.
Finally, If your function is work as an API, and you need a frontend JS to execute it, try with Blob class on JS.
You can indeed use a StreamedResponse to get it rid of this issue. About the fact that the whole .wip file content being displayed because of the flush, try to call ob_flush before

Zend Framework 3: create download link for generated file

I'm writing an app that lets the user upload an Excel file. It checks the file for errors, then, if no errors are found, it uploads the contents to a database. If it does find errors, the cells containing errors are colored red, then the file is saved. I then want to create a download link to this file so the user can check where they made mistakes.
The problem is that I am not sure how to create this link and where to store the file. I modify the file like this:
foreach ($badCells as $bcell) {
$sheet->getStyle($bcell)->applyFromArray(array(
'fill' => array(
'type' => \PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => 'FF4444')
)
));
}
And then save it with
$objWriter->save($dldir . $formData['upload']['name']);
$dldir is created with
$dldir = "/download/";
if (file_exists($dldir)) {
if (!is_dir($dldir)) {
unlink($dldir);
mkdir($dldir);
}
} else {
if(!is_dir($dldir)) {
mkdir($dldir);
}
}
Is this even the right way to do this? Can I store the files in any old folder or do they have go somewhere specific? How do I create the link to the specific file in the view for the user and make it accessible so they can download it?
I may be wrong .
For file upload i use this library Gargron/fileupload
The function bellow help to upload file to a specific folder and return full link of the file. You can save the link in DB
function uploadFile ($file){
$validator = new \FileUpload\Validator\Simple('5M');
$pathresolver = new \FileUpload\PathResolver\Simple($_SERVER['DOCUMENT_ROOT'].'/upload_folder');
$filesystem = new \FileUpload\FileSystem\Simple();
$fileupload = new \FileUpload\FileUpload(file, $_SERVER);
$fileupload->setPathResolver($pathresolver);
$fileupload->setFileSystem($filesystem);
$fileupload->addValidator($validator);
$md5Generator = new \FileUpload\FileNameGenerator\MD5 (true);
$fileupload->setFileNameGenerator($md5Generator);
list($files) = $fileupload->processAll();
foreach($files as $file){
if ($file->completed) {
return $_SERVER['DOCUMENT_ROOT'].'/upload_folder/'.$file->getFileName()) ;
}
}
}
Thanks for the help, I managed to figure it out over the weekend. Here's how I did
it:
$filename = join(DIRECTORY_SEPARATOR, array($dldir, $formData['upload']['name']));
$objWriter->save(str_replace(__FILE__,$filename,__FILE__));
This is how I save the file, using DIRECTORY_SEPARATOR so it will work correctly on both Windows and Linux.
return $this->redirect()->toRoute('import', ['action' => 'reject'],['query' => ['q' => 'file', 'name' => $filename]]);
In the controller, I redirect the route to the correct action and pass the file name on to it via a query URL.
public function rejectAction()
{
$filename = $this->getRequest()->getQuery('name', null);
return new ViewModel(array('filename' => $filename));
}
There, I obtain said file name through getRequest()->getQuery() and pass it on to the viewmodel.
Right-click here and choose 'Save As' to download your file.
And finally, this is how it shows the link in reject.phtml.
Downloading only works with right click and save as, I suspect I will have to write some sort of file handler to make ZF produce the correct headers for a normal left click download.

Cakephp calling function from view

I have the following function:
public function make_order($id = null){
if($this->request->is('post')){
if(isset($id)){
$single_product = $this->Product->find('first', array('Product.id' => $id));
$this->placeOrder($single_product);
}else{
$product_array = $_SESSION['basket'];
foreach($product_array as $product){
$this->placeOrder($product);
}
}
}
}
private function placeOrder($product){
$order_array = array();
$order_array['Order']['Product_id'] = $product['Product']['id'];
$order_array['Order']['lejer_id'] = $this->userid;
$order_array['Order']['udlejer_id'] = $product['users_id'];
$this->Order->add($order_array);
}
Now these two function are not "connected" to a view but i still need to call them from within another view
For this ive tried the following:
<?php echo $this->Html->link(__('Bestil'), array('action' => 'make_order')); ?>
However this throws an error saying it couldnt find the view matching make_order and for good reason ( i havnt created one and i do not intend to create one)
My question is how do i call and execute this function from within my view?
At the end of your make_order function, you'll either need to:
a) specify a view file to render, or
b) redirect to a different controller and / or action, that does have a view file to render.
a) would look like this:
$this->render('some_other_view_file');
b) might look like this (note: setting the flash message is optional)
$this->Session->setFlash(__('Your order was placed'));
$this->redirect(array('controller' => 'some_controller', 'action' => 'some_action'));
You can turn auto-rendering off by setting $this->autoRender = false; in your controller's action (make_order() in this case). This way you don't need a view file, and you can output whatever you need.
The problem is that nothing will be rendered on the screen. Therefore, my advice is to have your "link" simply call a controller::action via AJAX. If that's not possible in your situation, then you'll have to either render a view in your make_order() method, or redirect to an action that will render a view.

Two (almost) identical pieces of code produce separate results

I have been working on a little MVC project to assist in my self-learning and I have come across an issue that completely baffled me. I made a blog section in this MVC-ish system and pulled user permissions from an ACL with no problem whatsoever.
I moved onto creating a member section and as soon as i added any permissions checking I get the following error from Chrome:
No data received
Unable to load the web page because the server sent no data.
Here are some suggestions:
Reload this web page later.
Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data.
I thought it was weird, so I double checked my error logs and nothing had shown up. So I decided to copy and paste the working blog code into the member file, reloaded and i got the EXACT same error, the only difference between the two files right now is the file name and the class name.
Here is the Blog code:
<?php
class blog extends frontController {
public $model;
public $user;
public function __construct()
{
parent::__construct();
$this->model = $this->autoload_model();
$this->user = $this->load_user();
$this->user->getUserRoles();
}
public function index()
{
//Will only list the latest post ;)
if(!$this->user->hasPermission('blog_access'))
{
$array = $this->model->list_posts();
if(empty($array))
{
$this->variables(array(
'site_title' => 'View Blog Posts',
'post_title' => 'Sorry but there are no posts to display'
));
} else {
$this->variables(array(
'site_title' => 'View Blog Posts',
'list' => $array[0],
'post_title' => $array[0]['entry_title'],
'link' => str_replace(' ', '_',$array[0]['entry_title']),
));
}
} else {
$this->variables(array(
'site_title' => 'Error :: Design Develop Realize',
'body' => 'Sorry, but you do not have permission to access this',
));
}
$this->parse('blog/list', $this->toParse);
}
This is the member file:
<?php
class member extends frontController {
public $model;
public $user;
public function __construct()
{
parent::__construct();
$this->model = $this->autoload_model();
$this->user = $this->load_user();
$this->user->getUserRoles();
}
public function index()
{
//Will only list the latest post ;)
if(!$this->user->hasPermission('blog_access'))
{
//$array = $this->model->list_posts();
if(empty($array))
{
$this->variables(array(
'site_title' => 'Design Develop Realize :: View Blog Posts',
'post_title' => 'Sorry but there are no posts to display'
));
} else {
$this->variables(array(
'site_title' => 'Design Develop Realize :: View Blog Posts',
'list' => $array[0],
'post_title' => $array[0]['entry_title'],
'link' => str_replace(' ', '_',$array[0]['entry_title']),
));
}
} else {
$this->variables(array(
'site_title' => 'Error :: Design Develop Realize',
'body' => 'Sorry, but you do not have permission to access this',
));
}
$this->parse('blog/list', $this->toParse);
}
In the member class, if I comment out $this->user = $this->load_user(); then the error disappears!!!
Just for reference here is that function:
protected function load_user()
{
if(!$this->loader->loaded['acl'])
{
$this->loader->loadCore('acl');
}
return $this->loader->loaded['acl'];
}
Any help or suggestions would be appreciated as I am stumped!
PS yes I do have error reporting set to cover everything and no it does not log anything!
EDIT: Because all files go through index.php I have placed the error reporting there:
<?php
error_reporting(E_ALL);
ini_set('date.timezone', "Europe/London");
require_once('system/library/loader.php');
$loader = new loader();
$loader->loadCore(array('frontController', 'routing'));
EDIT 2: loadCore() is below
public function loadCore($toLoad, $params = false)
{
//important task first, check if it is more then 1 or not
if(is_array($toLoad))
{
//more then one so lets go to the task!
foreach($toLoad as $file)
{
if(file_exists('system/library/' . $file . '.php'))
{
require_once('system/library/' . $file . '.php');
if($params)
{
$this->loaded[$file] = new $file($params);
} else {
$this->loaded[$file] = new $file;
}
} else {
trigger_error("Core File $file does not exist");
}
}
} else {
//Phew, less work, it is only one!
if(file_exists('system/library/' . $toLoad . '.php'))
{
require_once('system/library/' . $toLoad . '.php');
if($params)
{
echo(__LINE__); exit;
$this->loaded[$toLoad] = new $toLoad($params);
} else {
$this->loaded[$toLoad] = new $toLoad;
}
}
}
}
Update: I modified loadCore so that if it was the acl being called it would use a try...catch() and that has not helped as it will not display an error just the same chrome and IE pages
Update 2: I have spoken with my host and it seems that everytime this error occurs, apache logs the following (not sure why I cannot see it in my copy of the logs!)
[Wed Feb 22 08:07:11 2012] [error] [client 93.97.245.13] Premature end
of script headers: index.php
You have commented out
//$array = $this->model->list_posts();
So now array is null and you are trying to use
'list' => $array[0],
'post_title' => $array[0]['entry_title'],
which definitely will generate an error.
EDIT:-
I see you have
'body' => 'Sorry, but you do not have permission to access this' , )); }
That is in second else which is a syntax error. and generates an output. If you have enabled, compress output in CI, that will cause this error.
"Premature end of script headers" are internal server errors. Which generally occurs when script breaks and does not send any HTTP headers before send the error messages. There might be several causes to this.
One might be output buffering. May be the server you are using buffers the output by default. I will suggest turning off the output_buffering using output_buffering = off on php.ini [docs here].
Make sure you are sending correct HTTP headers also
print "Content-type: text/html\n\n";
There are few more suggestion on this link.
To learn more about this error, go here.
Hope it helps
I'd be interested in seeing what's inside the loadCore function.
Have you used error_log anywhere? It might help shed some light on the issue.
Have you tested this page in different browsers? Googled your error, and it's indicating that it may be chrome specific?
Your statement that commenting out the loadCore('acl') is interesting, so obviously I would start there. You're sure that it is getting the system/library/acl.php page via the loader? Aka, it is triggering that line 2 below the exit in loadCore()? var_dump the return imo to make sure you're getting the object.
First of all. This error is produced when your server disconnect before it send any data.
A few suggestions.
your code is broken and let crash the application
your error logging should be enhanced by NOTICES
write tests to check every part
u should enable and use a debugger (zend_debugger, xdebug)
post a few more connection infos (e.g. wget -O - --debug 'url')
There is/was a special chrome issue for that problem
http://www.google.pl/support/forum/p/Chrome/thread?tid=3aa7b40eb01a95c8&hl=en#fid_3aa7b40eb01a95c80004ae797939c267
I suggest checking whether there are any blank lines before the tags.
What file names are you using?, are there any conventions you have to follow to fit a framework you might be using?
I wonder if this is a server problem and not a code problem?
This thread suggests that the server error you are seeing (500 premature end to headers) could be the result of Apache logs that are too full and need to be rotated. However it really could be anything - it seems to suggest simply that the script returns no output at all to the browser.
The other thing I'd check is file permissions, and the functioning of the include_once and file_exists in the loadCore method, as that looks the likeliest area to cause problems that might stop the script without even throwing a php error.
Maybe it´s a character/encoding error, open both files with notepad++ , goto Encoding, then select Convert to UTF-8, save the file and test it again.
Good Luck!

Zend Framework: image upload

I want to upload an image with Zend Framework version 1.9.6. The uploading itself works fine, but I want a couple of other things as well ... and I'm completely stuck.
Error messages for failing to upload an image won't show up.
If a user doesn't enter all the required fields but has uploaded an image then I want to display the uploaded image in my form. Either as an image or as a link to the image. Just some form of feedback to the user.
I want to use Zend_ Validate_ File_ IsImage. But it doesn't seem to do anything.
And lastly; is there some automatic renaming functionality?
All ideas and suggestions are very welcome. I've been struggling for two days now.
These are simplified code snippets:
myform.ini
method = "post"
elements.title.type = "text"
elements.title.options.label = "Title"
elements.title.options.attribs.size = 40
elements.title.options.required = true
elements.image.type = "file"
elements.image.options.label = "Image"
elements.image.options.validators.isimage.validator = "IsImage"
elements.submit.type = "submit"
elements.submit.options.label = "Save"
TestController
<?php
class Admin_TestController extends Zend_Controller_Action
{
public function testAction ()
{
$config = new Zend_Config_Ini(MY_SECRET_PATH . 'myform.ini');
$f = new Zend_Form($config);
if ($this->_request->isPost())
{
$data = $this->_request->getPost();
$imageElement = $f->getElement('image');
$imageElement->receive();
//$imageElement->getValue();
if ($f->isValid($data))
{
//save data
$this->_redirect('/admin');
}
else
{
$f->populate($data);
}
}
$this->view->form = $f;
}
}
?>
My view just echo's the 'form' variable.
First, put this at the start of your script:
error_reporting(E_ALL);//this should show all php errors
I think the error messages are missing from the form because you re-populate the form before you display it. I think that wipes out any error messages. To fix that, remove this part:
else
{
$f->populate($data);
}
To show the uploaded image in the form, just add a div to your view template, like this:
<div style="float:right"><?=$this->image?></div>
If the image uploaded ok, then populate $view->image with an img tag.
As for automatic re-naming, no, it's not built in, but it's very easy. I'll show you how below.
Here's how I handle my image uploads:
$form = new Zend_Form();
$form->setEnctype(Zend_Form::ENCTYPE_MULTIPART);
$image = new Zend_Form_Element_File('image');
$image->setLabel('Upload an image:')
->setDestination($config->paths->upload)
->setRequired(true)
->setMaxFileSize(10240000) // limits the filesize on the client side
->setDescription('Click Browse and click on the image file you would like to upload');
$image->addValidator('Count', false, 1); // ensure only 1 file
$image->addValidator('Size', false, 10240000); // limit to 10 meg
$image->addValidator('Extension', false, 'jpg,jpeg,png,gif');// only JPEG, PNG, and GIFs
$form->addElement($image);
$this->view->form = $form;
if($this->getRequest()->isPost())
{
if(!$form->isValid($this->getRequest()->getParams()))
{
return $this->render('add');
}
if(!$form->image->receive())
{
$this->view->message = '<div class="popup-warning">Errors Receiving File.</div>';
return $this->render('add');
}
if($form->image->isUploaded())
{
$values = $form->getValues();
$source = $form->image->getFileName();
//to re-name the image, all you need to do is save it with a new name, instead of the name they uploaded it with. Normally, I use the primary key of the database row where I'm storing the name of the image. For example, if it's an image of Person 1, I call it 1.jpg. The important thing is that you make sure the image name will be unique in whatever directory you save it to.
$new_image_name = 'someNameYouInvent';
//save image to database and filesystem here
$image_saved = move_uploaded_file($source, '/www/yoursite/images/'.$new_image_name);
if($image_saved)
{
$this->view->image = '<img src="/images/'.$new_image_name.'" />';
$form->reset();//only do this if it saved ok and you want to re-display the fresh empty form
}
}
}
First, have a look at the Quick Start tutorial. Note how it has an ErrorController.php that will display error messages for you. Also note how the application.ini has these lines to cause PHP to emit error messages, but make sure you're in the "development" environment to see them (which is set in public/.htaccess).
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
Second, ZF has a renaming filter for file uploads:
$upload_elt = new Zend_Form_Element_File('upload');
$upload_elt
->setRequired(true)
->setLabel('Select the file to upload:')
->setDestination($uploadDir)
->addValidator('Count', false, 1) // ensure only 1 file
->addValidator('Size', false, 2097152) // limit to 2MB
->addValidator('Extension', false, 'doc,txt')
->addValidator('MimeType', false,
array('application/msword',
'text/plain'))
->addFilter('Rename', implode('_',
array($this->_user_id,
$this->_upload_category,
date('YmdHis'))))
->addValidator('NotExists', false, $uploadDir)
;
Some of the interesting things above:
mark the upload as required (which your .ini doesn't seem to do)
put all the uploads in a special directory
limit file size and acceptable mime types
rename upload to myuser_category_timestamp
don't overwrite an existing file (unlikely, given our timestamp scheme, but let's make sure anyway)
So, the above goes in your form. In the controller/action that receives the upload, you could do this:
$original_filename = $form->upload->getFileName(null, false);
if ($form->upload->receive()) {
$model->saveUpload(
$this->_identity, $form->upload->getFileName(null, false),
$original_filename
);
}
Note how we capture the $original_filename (if you need it) before doing receive(). After we receive(), we do getFileName() to get the thing that the rename filter picked as the new filename.
Finally, in the model->saveUpload method you could store whatever stuff to your database.
Make sure your view also outputs any error messages that you generate in the controller: loading errors, field validation, file validation. Renaming would be your job, as would other post processing such as by image-magick convert.
When following lo_fye's listing I experienced problems with custom decorators.
I do not have the default File Decorator set and got the following exception:
Warning: Exception caught by form: No file decorator found... unable to render file element Stack Trace:
The Answer to this is that one of your decrators must implement the empty interface Zend_Form_Decorator_Marker_File_Interface
Also sometimes it happens to bug when using an ajax request. Try it without an ajax request and don't forget the multipart form.

Categories