Codeigniter Controller return to previous page - php

I'd like to ask you how can I instead of $this->load->view('some_view.php') at the end of controller code, return user to page from where he invoked controller method? Simple return statement is not working.
ie.
public function someMethod($IDCustomer) {
$this->Some_modal->persist($IDCustomer);
// how to return to previous page instead of line after?
// i've used $this->load->view('someView.php');
}

This should help http://www.codeigniter.com/user_guide/libraries/user_agent.html
$this->load->library('user_agent');
if ($this->agent->is_referral())
{
echo $this->agent->referrer();
}
or straight PHP:
redirect($_SERVER['HTTP_REFERER']);

I've found answer on some thread.
In the page that you want to go back to you can do:
$this->session->set_userdata('referred_from', current_url());
Then redirect back to that page
$referred_from = $this->session->userdata('referred_from');
redirect($referred_from, 'refresh');

Tried return redirect()->to($_SERVER['HTTP_REFERER']); , this would work well.

In Codeigniter 4 You can use previous_url() function from url helper
find more https://codeigniter.com/user_guide/helpers/url_helper.html

I've tried header('location:'.$_SERVER['HTTP_REFERER']); and it's working quite well.
Just a one-liner plain old PHP code.

Use the REDIRECT_QUERY_STRING alternative of HTTP_REFERRER:
// set in session redirect back URL in your common is_logged_in function if user is not logged in
$CI->session->set_userdata('redirect_back', $_SERVER['REDIRECT_QUERY_STRING']);
// below code user after successful login in auth.php library
if($this->ci->session->userdata('redirect_back')){
$redirectBackUrl = $this->ci->session->userdata('redirect_back');
$this->ci->session->unset_userdata('redirect_back');
redirect(base_url() . $redirectBackUrl);
}

Related

Reload current URL in Codeigniter After Submit The Form

I have one form in my view.php file. Its URL like https://example.com/members/view/1, https://example.com/members/view/2 etc. When I submit form its calling model through controller like below
public function insert_comments(){
$data=$this->input->post();
$this->load->model('work_model');
$result=$this->work_model->insert_comments($data);
if($result)
{
$this->session->set_flashdata('insert_comments','your comments succesfully');
$this->session->set_flashdata('succesfully','alert-success');
$this->load->view('add_coments');
}
else{
$this->session->set_flashdata('insert_comments','your comments failed');
$this->session->set_flashdata('succesfully','alert-danger');
$this->load->view('add_coments');
}
}
}
and model is like below
public function insert_comments($array)
{
return $this->db->insert('comments',$array);
}
Currently its working fine and on form submit its loding view called add_comments, instead I want reload/refresh current page. I am not able to get idea of how I can do it, let me know if someone can help me for do it.
Thanks!
According to this answer, in the controller you can use:
redirect($this->uri->uri_string());
use this :
redirect($_SERVER['REQUEST_URI'], 'refresh');
Whenever you are reloading or redirecting a page you should always use the redirect() method instead of loading a view.
Redirection basically uses the header() method of core PHP and redirection will never execute the code blocks written beyond the redirect() method. But in the case of loading the view, it can execute until the end of the code block.
In your code, replace the line $this->load->view('add_coments'); with the redirection to the desired controller
redirect('your-controller','refresh');
I hope that helps you.

How to use PHP variable in href?

I made a FacebookConnect class in PHP for a project. It's working well, but the problem is that I'm unable to use the href correctly.
Connect with fb
I'm trying to call a method from one of my controllers in the href. I want to make it so that when I click on the button, it starts the login process.
public function _loginFacebook()
{
$connect = new FacebookConnect($appid,$app_secret);
$user = $connect->connect('http://localhost/washare/?site=public&module=Compte&action=profil');
if (is_string($user)) {
return $user;
}
}
In fact, I wanted to use the $user variable (which is a redirect URL) in the href directly, but iI guess I'm doing this wrong. Can someone help me?
Function _loginFacebook is called? If so, what part of code is achieved?
You can use header for redirecting on php.
<?php
header('Location: mapeamento.php');
?>

Redirect toUrl does not work (zf2)

I have a problem with a redirect in Zend Framework 2.
when a user enters a url like http//mysite.test/lorem, he will be redirected to http//mysite.test/news/view/lorem-ipsum.
the code:
$redirecttable = $sm->get('Redirect\Model\RedirectTable');
$route = $redirecttable->getRedirectByRoute($this->params()->fromRoute('page'));
if($route) {
// $route->getToroute() returns "news/view/Lorem-Ipsum"
return $this->redirect()->toUrl( $route->getToroute() );
}
Am I making a stupid mistake here?
The toUrl method redirect to a complete url, but you're sending part of url. You can use $this->redirect()->toRoute($route,$params) for redirecting to a route. reference
If you want to use toUrl method, try this code:
return $this->redirect()->toUrl( $this->getRequest()->getUri()->toString().$route->getToroute() );
Use toRoute() instead of toUrl():
return $this->redirect()->toRoute($route->getToroute())

How to set returnUrl value in Yii

I am using Yii and the problem I am getting is with the Yii::app()->user->returnUrl. It always returns me to the index.php page.
How can I set its value to the page which requested the current page as I do not know from which page user has visited the current page?
You can use Yii::app()->request->urlReferrer to see where the user came from.
public function beforeAction()
{
Yii::app()->user->returnUrl = Yii::app()->request->urlReferrer;
return parent::beforeAction();
}
Be careful, if the user came from a 3rd party site, then this will redirect them away from your site.
For those using Yii2
Yii::$app->user->returnUrl = Yii::$app->request->referrer;
There is no such thing as: Yii::app()->user->urlReferrer
It should be: Yii::app()->request->urlReferrer or Yii::app()->request->requestUri (current page)
So try this:
Yii::app()->user->returnUrl = Yii::app()->user->urlReferrer;
Or this one (which I personally prefer):
Yii::app()->user->returnUrl = Yii::app()->request->requestUri;
I created a Yii extension to manage return URLs, you can find it here:
https://github.com/cornernote/yii-return-url#yii-returnurl
It's an improvement over the way Yii handles it because it stores the return url in the GET/POST data instead of the SESSION. This means that if you have multiple tabs open then each can have it's own return url.
You can use like this
$http = new CHttpRequest();
$referrer_url = $http->getUrlReferrer();
$this->redirect($referrer_url);
Hope this will help you
You can also do like that
Yii::app()->user->returnUrl = Yii::app()->request->urlReferrer;
$this->redirect(Yii::app()->user->returnUrl);
For those who still struggling with returning to previous page: You have to create a property in login model $referer, and at the time when you initialize your Login model you set this property to Yii::$app->request->referrer. You have to go this way because after you submit your form your referrer does change to current page, and since it is null, it return you to index action. So the way how to pass the return URL is to store it in the hidden field at the form, so when you submit the form you have this URL loaded and you can perform action to return $this->goBack($form->referer ? $form->referer : null).
Here is the code:
Login model:
public $referer;
Controller action:
$model = new Login();
$model->referer = Yii::$app->request->referrer;
...
if($model->load(Yii::$app->request->post()){
...
if($model->save()){
return $this->goBack((($model->referer) ? $model->referer : null));
}
}
View login.php:
<?= $form->field($model, 'referer')->hiddenInput()->label(false) ?>

PHP/codeigniter - use of exit()

I have a few pages that require login, so all controllers that link to these pages start with
$this->checkSession();
//...rest of the code
CheckSession should verify the session is still live, otherwise display a message and stop the execution of the rest of the code in the controller:
function checkSession()
{
if (!$this->session->userdata('is_logged_in'))
{
//the session has expired!
$data['main'] = 'confirmation_message';
$data['title'] = "Session expired";
$this->load->vars($data);
$this->load->view('template');
exit();
}
}
.
I was expecting these instructions to happen in sequence, but I only get a blank page.
How can I make sure exit() gets executed only after all views are loaded?
In this case Pedro is correct. If they are not logged in just redirect them, it's even better if you can use Public/Admin named base controllers to stop you having to do this in each separate protected file.
Generally speaking though, if you use exit() it will stop the Output library for running. If you just want to stop the current controller from executing but allow output of the controller you can use return in exactly the same way.
function checkSession()
{
return (bool) $this->session->userdata('is_logged_in');
}
Then simply:
if(!$this->checkSession())
{
//the session has expired!
$data['main'] = 'confirmation_message';
$data['title'] = "Session expired";
$this->load->vars($data);
$this->load->view('template');
return;
}
exit() should only ever be used if you really want instant death of your application's execution for debugging, error reporting, etc.
In this case you should not use exit, what you should do if the session is not valid is redirect your app using example:
redirect('/init/login/','refresh');
I had a similar problem. Where I wanted to stop the user to due to no login. But I wanted to offer a list of links for them not simply redirect them to a login page. I am using CI version 1.7.2 and the $this->_output() $this->display->_output() and $this->output->_display() solutions did not work for me. I was however to get my results using the $this->output->get_output() function.
$this->load->vars($data);
$this->load->view('template');
die($this->output->get_output());
$this->output->_display();
exit();
Is the correct answer! Thanks to Sam Sehnert... It's hidden in the comments so thought I'd re-post.
I don't know enough about codeigniter's workflow but it seems to me that you want to redirect to the login page instead of trying to render it. Evidently, none of the code you supplied sends the template to the browser by the time exit() is called.
exit() cuts your scrip there and the actual _output() function of the controller is never called. What you need to do is add action in one of your controllers for example the user login screen and redirect there. You can use the flashdata function from the Session - http://codeigniter.com/user_guide/libraries/sessions.html to pass your message and then catch it inside your view and display it.
Another way which is not very smart but should work is to forcefully call the output function.
function checkSession()
{
if (!$this->session->userdata('is_logged_in'))
{
//the session has expired!
$data['main'] = 'confirmation_message';
$data['title'] = "Session expired";
$this->load->vars($data);
$this->load->view('template');
$this->_output();
exit();
}
}
Actually in the newest CI function to manually call output class is
$this->display->_output();
and don't be worried - it handles caching, content will also be properly gzipped if you set so in config
I usually add and extended controller with login logic that handles login functions, so that if a normal controller is one that is needing an auth then the login method is called automatically and the original content is not displayed. It's a good solution if you would like to stay on the page the user tried to access without redirecting (and then posting him back to the same page)
Put the code in a variable and write it.
$html = $this->load->view('template',null,true);
echo $html;
exit();

Categories