cakephp does not save cookie - cakephp

I have this simple code in my AppController beforeFilter function, to set a cookie
$this->Cookie->name = 'MyCookie';
$this->Cookie->time = '1 hour';
$this->Cookie->domain = 'example.com';
$myCookie = $this->Cookie->read('my_cookie');
if ( empty($myCookie) ) {
$this->Cookie->write('my_cookie', 'cookieValue', true);
} else {
echo $myCookie;die;
}
So, as I refresh the page for the second time it should echo the cookie's value. But it does not. The output is nothing. Any ideas what can be the problem ?
I use cake 2.3.1. Cookie component is included. Debug level is 3 and there are no errors. I have checked the cake logs file - nothing there.
Thanks

Related

Reset an entity (or create a new empty entity) in controller after saving

How do you reset an entity after saving it if there is not a redirect after saving (if you stay on the same action/page)?
Example: I have a page listing all users. On the same page there is the form to add a new user.
public function index() {
$this->set('listallusers', $this->Users->find('all'));
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data );
if ( $this->Users->save($user) ) {
$this->Flash->succeed('User saved.');
// line 8
} else {
$this->Flash->error('There is an error.');
}
}
$this->set('user', $user);
}
I tried to add $user = ''; after the flash message in line 08, as well as $user = $this->Users->newEntity();
But the form on the page is still containing/showing the values of the last saved user (I want to have an empty form when the saving was successfull).
I don't know how to mark a comment as the answer to my question, so I quote it:
You don't just stay on the same page. A save is the result from a POST, thus you need to make a GET (redirect) afterwards to follow the PRG pattern, which you must follow for several reasons to avoid other issues coming up. Then your issue resolves itself. So ALWAYS redirect, in your case just to the same URL again. Problem solved - by design. – mark
Thank you #mark

How to set cookie in cakephp

I want to set cookie but unable to set
i have also used this public $components = array('Cookie');
i used in UsersController $this->Cookie->write('name', 'Larry');
echo on another controller echo $this->Cookie->read('name');
but there is no result
please suggest how to set cookie in cake php
thank Sanjib
It looks as if you used this tutorial for cookies: http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html
What you probably missed is setting up the cookieComponent, this of course is necessary in order for you to use cookies.
public $components = array('Cookie');
public function beforeFilter() {
parent::beforeFilter();
$this->Cookie->name = 'baker_id';
$this->Cookie->time = 3600; // or '1 hour'
$this->Cookie->path = '/bakers/preferences/';
$this->Cookie->domain = 'example.com';
$this->Cookie->secure = true; // i.e. only sent if using secure HTTPS
$this->Cookie->key = 'qSI232qs*&sXOw!adre#34SAv!#*(XSL#$%)asGb$#11~_+!##HKis~#^';
$this->Cookie->httpOnly = true;
$this->Cookie->type('aes');
}
If you comment out
$this->Cookie->type('aes');
you should find the problem gone.
In your AppController src\Controller\AppController.php
put var $components = array('Cookie');
or you can set and retrieve cookie using original PHP.
For people using CakePHP 4.x: Instead of using the cookie component, you now need to set a cookie to the Response object and fetch it via the Request object:
// Create cookie and set it to the Response object
$cookie = (new Cookie('name'))
->withValue('Larry');
$this->setResponse($this->getResponse()->withCookie($testCookie));
// Fetch a cookie's value from the Request object
$name = $this->getRequest()->getCookie('name'); // 'Larry'
Note that setting cookies will not work when using debug() or other output (e.g. echo), as headers cannot be sent if any output is already sent. You should get a warning about this as well.
For more information see this answer, or check the documentation on setting cookies and getting cookies
.

Integrating a file browser into ckeditor & CakePHP

recently found an article in http://hashtwo.com/blog/integrating-a-file-browser-into-ckeditor-cakephp to integrate a file browser into ckeditor (file manager of core five labs )
I followed the steps but i get an error when I click the browse server button,
Missing Controller:
Error: CkeditorController could not be found.
I had the same error at some point during my setup, but I don't seem to recall what was it and how I fixed it. Let me know if my next solution does not fix your problem and I will investigate a little more:
First I followed the following tutorial which worked well, but missed the Authentication part: http://labs.corefive.com/projects/filemanager/
Then I used the tutorial you referenced, except for the last section of code provided. Instead I added the following code directly to my view page: admin_add.ctp
<?php echo $form->textarea('body', array(/*'class'=>'ckeditor', */'id' => 'body', 'class' => 'body')) ?>
<?php
include_once 'ckeditor/ckeditor.php' ;
//require_once 'ckfinder/ckfinder.php' ;
//$initialValue = 'Default value goes here' ;
$ckeditor = new CKEditor() ;
$ckeditor->basePath = '/ckeditor/' ;
$ckeditor->config['filebrowserBrowseUrl'] = '/ckeditor/filemanager/index.html';
$ckeditor->config['filebrowserUploadUrl'] = '/ckeditor/filemanager/connectors/php/filemanager.php';
$ckeditor->config['filebrowserImageBrowseUrl'] = '/ckeditor/filemanager/index.html?type=Images';
$ckeditor->config['filebrowserImageUploadUrl'] = '/ckeditor/filemanager/connectors/php/filemanager.php?command=QuickUpload&type;=Images';
$ckeditor->config['filebrowserWindowWidth'] = '800';
//CKFinder::SetupCKEditor( $ckeditor,'/ckfinder/' ) ;
// This will replace CakePHP textarea listed above.
$ckeditor->replace('body');
?>
Also, for the Auth Section of his tutorial I changed it to match my requirements:
function auth() {
session_name("CAKEPHP");
session_start();
if(isset($_SESSION['Auth']['User']) )
{
//Since CKEditor for me is only used in the admin section
//I make sure only admins can access it, group_id=1
if($_SESSION['Auth']['User']['group_id'] == 1)
{
return true;
}
}
return false;
}
If it tries to find a controller this means it can not access the editors file or folder and instead the dispatcher of CakePHP gets the request and tries to load a fckeditor controller.
This means you'll need to place the editor in the right directory (for example app/webroot/fckedtor/) or use the correct url to access it.

CakePHP not saving my cookie

In my users controller I am trying to put in place the remember me functionality on login. IT seems pretty simple set a cookie look for the cookie when the user visits the login page and if it exists log them in. However, Cake is not saving the cookie, at least not that I can see, and when I revisit the page I am not auto logged in.
To test this I have the following code:
$cookie=$this->read('Auth.User');
if(empty($cookie) and !empty($this->data)){
if($this->Auth->login()) {
if(!empty($this->data['User']['remember_me'])){
$cookie = array('id' => $this->Auth->user('id'),
);
$expires=strtotime($this->appConfigurations['remember_me'],time());
$this->Cookie->write('Auth.User', $cookie, false, $this->appConfigurations['remember_me']);
}
}
}
Now right after I set this cookie I can place a $this->cookie->read('Auth.User'); and get the value of this cookie, however it does not show up in the browsers (Chrome, FireFox) cookie list.
If I use plain PHP cookies, via setcookie() I can see the cookie but of course the Cake Cookie read does not work with those cookies. What should I look for to resolve this issue?
I did find a work around, but I don't like it because it just bypasses the framework. I found out how cake is creating the cookies and for these cookies I use cakes cookie creation algorithm in my code and use setcookie() to do the setting. Just for anyone else that may want or need to use the work around:
$cookieValue=$this->Auth->user('id');
setcookie('CakeCookie[Auth][User]',$cookieValue,$expires,'/');
Now you can use cakes cookie component to read the value. There is more you have to change if your value is an array, read through the cookie.php code to see what you would need to do. Also I left out the encryption that too can be found in the cookie.php and your apps settings. For this issue I do not need array values since I am only store the users ID. and I did put in place encryption unlike above.
I would still like to know why the component is not working though.
The following login action works well for me :
function login() {
$cookie = $this->Cookie->read('Auth.User');
debug($cookie); // Just a test
if ($this->Auth->user('id')) {
if(!empty($this->data)) {
$cookie = array(
'username' => $this->data['User']['username'],
'password' => $this->data['User']['password']
);
$this->Cookie->write('Auth.User', $cookie, false, '+2 weeks');
}
$this->redirect('/');
}
elseif (!empty($cookie)) {
if ($this->Auth->login($cookie)) {
$this->redirect('/');
}
}
}
Does it work on your side ?

Cakephp html2pdf auth problem

i am new with cake but i´ve somehow managed to get through so far. After i´ve figured out that html2pdf is a convienient way to produce pdf documents out of Cakephp, i´ve installed html2ps/pdf and after some minor problems it worked. So now i am coming now to the point that if i don´t modify my controllers beforeRender function like:
function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('download','view');
}
i just see my loginpage in the pdf i´ve created. Setting within my beforeRender function the $this->Auth->allow value opens obviously erveryone the way to get a perfect pdf without being authorized. The whole controller looks like this:
<?php
class DashboardController extends AppController {
var $name = 'Dashboard';
var $uses = array('Aircrafts','Trainingplans',
'Fstds','Flights','Properties','Person');
function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('download','view');
}
function view() {
/* set layout for print */
$this->layout = 'pdf';
/* change layout for browser */
if> (!isset($this->params['named']['print']))
$this->layout = 'dashboard';
/* aircrafts */
$this->Aircrafts->recursive = 0;
$aircrafts =$this->Aircrafts->find('all');
$this->set('aircrafts',$aircrafts);
.... and so on....
$this->set('person_properties',$person_properties);
}
function download($id = null) {
$download_link = 'dashboard/view/print:1';
// Include Component
App::import('Component', 'Pdf');
// Make instance
$Pdf = new PdfComponent();
// Invoice name (output name)
$Pdf->filename = 'dashboard-' . date("M");
// You can use download or browser here
$Pdf->output = 'download';
$Pdf->init();
// Render the view
$Pdf->process(Router::url('/', true) . $download_link);
$this->render(false);
}
}
?>
So in my opinion the $Pdf->process call get´s the data by calling more or less the view, but this process is not logged in, or in other words not authorized to get the data i want to render into the pdf. So the question is now how to get it done by not opening my application to everyone.
Best regards, cdjw
Edit:
You could do something like this:
if($this->Session->check('Auth.User')) {
// do your stuff
} else {
// do something else
}
You could check for 2 things before rendering /view:
a valid session (a user is logged in)
a valid security token that you pass from your download action as a named parameter
For the security token, just make up a long random string.
As the PDF is rendered on the same server, the token will never be known in the open and provide sufficient security.
Hope this is a working idea for you.
I had this similar issue, and this is how I handled it...
I first noticed that the process call of the PdfComponent was doing a request from the same server, so I tricked CakePHP on allowing the view only for requests being made from the server itself.. like this:
public function beforeFilter() {
if ($this->request->params['action']=='view'&&$_SERVER['SERVER_ADDR']==$_SERVER['REMOTE_ADDR']) { // for PDF access
$this->Auth->allow('view');
}
}
You should put
$this->Auth->allow('download','view');
inside AppController. rather than place where are you using now.
function beforeFilter() {
$this->Auth->allow('download','view');
....
}

Resources