CakePHP redirect to blank page - php

I have a problem with the redirection with cakephp 2.x.
When I execute the function below the redirect it works perfectly:
public function test() {
$this->redirect(array('controller' => 'pages','action' => 'index'));
}
But when I execute a trasaction with the database (add, modify and delete), the function redirect me to a blank page:
public function delete($id = null) {
$this->Post->id = $id;
if (!$this->Post->exists()) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->Post->deleteAll(array('Post.id' => $id), false)) {
$this->Session->setFlash(__(" success."), 'flash', array('class' => 'alert alert-success'));
} else {
$this->Session->setFlash(__("error."), 'flash', array('class' => 'alert alert-danger'));
}
$this->redirect(array('controller' => 'pages','action' => 'index'));
}
Redirection does not work.
Thank you for helping me

Have you check with the debug 1 or 2 , if it shows some type of error.Moreover why are you using deleteAll for deleting single record, use delete method instead of deleteAll.
$this->Post->delete($id);

Please, check if there is anything printed before redirect acting, even if it is a space which can prevent redirect.

Related

Bad redirectUrl at login with CakePHP

This is what I did to reproduce my problem:
Login (redirection at page foo)
Click and go to page bar
Logout
Login again
The redirected page is bar (it should be foo)
This is what I did:
AppController.php
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'loginRedirect' => [
'controller' => 'Dashboard',
'action' => 'index'
]
]);
UsersController.php
public function login($reset = null) {
$this->layout = 'login';
$this->set('reset', $reset);
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
// IMPORTANT!
// Here I'm setting a different redirect url. The book says
// that $this->Auth->redirectUrl() will read the Auth.redirect
// session. I wanted my admin to login into a different page
if($session->read('Auth.User.role_id') === 3) {
$session->write('Auth.redirect', '/users/system_administrator_index');
}
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
} else {
$this->Flash->error('Oops', ['key' => 'auth']);
}
}
}
public function logout() {
return $this->redirect($this->Auth->logout());
}
I tried to use $session->destroy(); in order to clear everything related to my session but I noticed anything.
Each time I retry to login, the server redirect me to the last page I visited the last time I was connected.
I found a workaround. Instead of using return $this->redirect($this->Auth->redirectUrl());, I do a manual redirection.
public function login($reset = null) {
$this->layout = 'login';
$this->set('reset', $reset);
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
if($user['role_id'] === 3){
return $this->redirect('/users/system_administrator_index');
}
return $this->redirect('/dashboard');
} else {
$this->Flash->error('Oops', ['key' => 'auth']);
}
}
}

Flash() method shows the message but not redirecting in CakePHP 2

In Controller
public function add(){
$this->loadModel('User'); //load model
if($this->request->is('post')){
$filename=$this->User->checkFileUpload($this->request->data);
$this->User->set($this->request->data); //set data to model
if ($this->User->validates()){
$datas = array(
'User' => array(
'name' => $this->request->data['User']['name'],
'email'=>$this->request->data['User']['email'],
'password'=>$this->request->data['User']['password'],
'image'=>$filename
)
);
$pathToUpload= WWW_ROOT . 'upload/';
move_uploaded_file($this->request->data['User']['image']['tmp_name'],$pathToUpload.$filename);
// prepare the model for adding a new entry
$this->User->create();
// save the data
if($this->User->save($datas)){
//$this->Session->setFlash('User Information has been saved!');
return $this->Flash('User Information has been saved!',array('action' => 'index'));
//return $this->redirect(array('action' => 'index'));
}
} else {
$errors = $this->User->validationErrors; //handle errors
}
}
//$this->layout = NULL;
$this->viewpPath='Users';
$this->render('add');
}
In above code, i used flash() method to direct a user to a new page after an operation. This method showing the message but not redirecting in given url.
Please help me. What am i doing wrong here for redirecting with help of flash() method?
flash() does not redirect, it renders. It is very similar to the render() function, it will continue the execution of the script, unlike the redirect() function.
but if you still want to use this
you should use following in config file.
Configure::write('debug', 0);
Update
after add this into main.php use like
$this->flash(__("Some message for the user here..."), array("action" => "index"));
it'll work perfactly . Follow this forrefrence
Render != Redirect
If you need to redirect to the referer page you can use:
$this->redirect($this->referer());
if you want redirect to different controller:
$this->redirect(('controller' => 'YOURCONTROLLER', 'action' => 'YOURACTION'));
or if you want redirect to different action in same controller:
$this->redirect(('action' => 'YOURACTION'));

App Name Showing Twice - Routing Issue or Login Function Issue?

I am having a small problem and I am not sure if its a routing issue or something is wrong with my login function. I have this ACL Plugin that I bought and integrated into my application. That said the login function is built into the plugin, so I edited my routing like so
Router::connect('/', array('plugin' => 'AuthAcl', 'controller' => 'users', 'action' => 'login', 'home'));
Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));
Now the login will work but when I login it appears like this localhost/app/app
Instead of localhost/app.
I do not see anything wrong with the routing.
My login function is as follows
public function login() {
$this->layout = 'admin_login';
$this->Session->delete('auth_user');
App::uses('Setting', 'AuthAcl.Model');
$Setting = new Setting();
$error = null;
$general = $Setting->find('first',array('conditions' => array('setting_key' => sha1('general'))));
if (!empty($general)){
$general = unserialize($general['Setting']['setting_value']);
}
$this->set('general',$general);
$user = $this->Auth->user();
if(!empty($user)){
$this->redirect($this->Auth->redirect());
}
if ($this->request->is('post')) {
if ($this->Auth->login()) {
if ((int)$this->request->data['User']['remember_me'] == 0){
$this->Cookie->delete('AutoLoginUser');
}else{
$this->Cookie->write('AutoLoginUser', $this->Auth->user(), true, '+2 weeks');
}
$this->redirect($this->Auth->redirect());
} else {
$error = __('Your username or password was incorrect.');
}
}
$this->set('error',$error);
Why am I not redirected correctly when I login.
Ok so here is what I did to fix the problem. I pointed to the controller where I wanted the users to be redirected. Thanks user221931!
$this->redirect($this->Auth->redirectUrl('auth_acl'));

CakePHP isAuthorized not working properley when passing arguments

I'm using isAuthorized to deny access to methods if the record id doesn't belong to the user. Profiles can have many documents and documents belong to one profile:
Controller/DocumentsController.php
public function add($id = null) {
if ($this->request->is('post')) {
$this->request->data['Document']['profile_id'] = $id;
$this->request->data['Document']['user_id'] = $this->Auth->user('id');
$this->Document->create();
if ($this->Document->save($this->request->data)) {
$this->Session->setFlash(__('The document has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The document could not be saved. Please, try again.'));
}
}
}
public function isAuthorized($user) {
if ($this->action === 'index') {
return true;
}
if (in_array($this->action, array('view', 'add', 'edit', 'delete'))) {
$document_id = $this->request->params['pass'][0];
if ($this->Document->isOwnedBy($document_id, $user['id'])) {
return true;
}
}
return parent::isAuthorized($this->Auth->user());
}
Model/Document.php
public function isOwnedBy($document, $user) {
return $this->field('id', array('id' => $document, 'user_id' => $user)) === $document;
}
I'm passing the profile id as $id to docments/add from one of my profile views via Cake link helper:
View/Profiles/view.ctp
echo $this->Html->link('New Document',
array('controller' => 'documents', 'action' => 'add',$profile['Profile']['id'])
);
What happens when I click on New Document from profiles/view is that it sends the request but doesn't redirect, just refreshes the page, or it redirects back to profiles/view, not sure which. My first guess is since I'm not defining the profile id in the isAuthorized callback within DocumentsController, isOwnedBy is returning false. Any suggestions on how to get the profile id in isAuthorized within DocumentsController?
Thanks in advance!
The solution to this is relativley easy. When using isAuthorized with parameters from another controller, be sure to reference the right model.
if ($this->Document->Profile->isOwnedBy($document_id, $user['id'])) {
return true;
}

CakePHP Check referer

I have the following code in my CakePHP app home controller:
public function index ()
{
if($this->referer(array('controller' => 'users', 'action' => 'logout')))
{
$this->layout = 'splash';
$this->set('title_for_layout', 'Goodbye');
$this->render('loggedout');
}
else
{
if (!$this->Auth->user())
{
$this->layout = 'splash';
$this->set('title_for_layout', 'Welcome to CreatHive');
$this->render('splash');
}
else
{
$this->layout = 'home';
$this->set('title_for_layout', 'CreatHive');
$this->render('index');
}
}
}
Basically it says if the user came from the logout action show the loggedout view but if not then check if they are logged in and either show the splash page or home page.
However it ALWAYS shows the logged out view regardless of being logged in or not or even coming from the logout action (even flushing sessions/cookies etc doesn't work)
Any ideas what the problem is as the code looks fine to me :/
Thanks
Change:
if($this->referer(array('controller' => 'users', 'action' => 'logout')))
To:
if($this->referer() == Router::url(array('controller' => 'users', 'action' => 'logout')))

Categories