I've try to use $this->session->set_flashdata('success') and it's not working after redirect to another function. Here is my code:
<?php
class Home extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->helper(array('url','form');
$this->load->library(array('session','template','form_validation');
}
}
/* My another function for form_validation and etc */
public function login(){
$this->set_login_rules();
if($this->form_validation->run()){
/* inserting data to database */
$this->session->set_flashdata('welcome');
redirect('home/welcome');
}
$this->template->display('home');
}
public function welcome(){
if($this->session->flashdata('welcome') !== FALSE){
echo "<script>alert('Flashdata Success! Welcome!</script>";
}
else{
echo "<script>alert('Flashdata Failed! Go Away!');</script>";
}
}
when I run the program, it shows alert Flashdata Failed! Go Away!
but the login data that I want to insert to database is added into the table.
one more thing, sometimes the flashdata is working. From 10 tries, 8-9 tries if show Flashdata Failed! Go Away!.
Can anybody tell me why this happend? And how can I fixed it?
You actually need to give some value to it, so:
$this->session->set_flashdata('welcome');
should be:
$this->session->set_flashdata('welcome', true);
or you can use the full message for example:
$this->session->set_flashdata('welcome', 'Successfully logged in');
etc...
See more info about flashdata here: https://ellislab.com/codeigniter/user-guide/libraries/sessions.html
From the Codeigniter documentation:
CodeIgniter supports "flashdata", or session data that will only be available for the next server request, and are then automatically cleared.
Your problem might be that when you redirect, the process takes more than one request, that clearing your flashdata.
Use regular session or query parameter.
Related
After logout, I tried to redirect for the home page. I tried to few ways, but not redirected.
class User extends BaseController
{
public function __construct()
{
helper('url');
}
for the logout function. I used three ways
redirect('/');
or
header("Location:".base_url());
or
route_to('/');
as per CI 4
use
return redirect()->to('url');
if you are using route then use
return redirect()->route('named_route');
I use this and it works
return redirect()->to(site_url());
In codeigniter 4 redirect()->to() returns a RedirectResponse object, which you need to return from your controller to do the redirect.
for ex.
class Home extends BaseController {
public function index() {
return redirect()->to('https://example.com');
}
}
I am new to CI4. In my case, I had to properly set $baseURL in App.php. For example, if the port is set incorrectly in your local development, it will just hang.
eg. public $baseURL = 'http://localhost:8888/';
Its worth saying that unlike the former CI3 redirect() function this one must be called from within a Controller. It won't work for example within a Library.
Update 2021
It is in fact possible to do this! Simply check that the returned response is an object and return it instead. So if a library returns a RedirectResponse, check it using the following code and return if applicable.
if (!empty($log) && is_object($log)){
return $log;
}
You could of course do get_class() to make sure the object is a type of RedirectResponse if there is any possibility of another object being returned.
If you using unnamed route:
$this->response->redirect(site_url('/user'));
'/user': It is my controller name. You can also used controller/function name.
Please look at the documentation
// Go back to the previous page
return redirect()->back();
// Go to specific URI
return redirect()->to('/admin');
// Go to a named route
return redirect()->route('named_route');
// Keep the old input values upon redirect so they can be used by the old() function
return redirect()->back()->withInput();
// Set a flash message
return redirect()->back()->with('foo', 'message');
// Copies all cookies from global response instance
return redirect()->back()->withCookies();
// Copies all headers from the global response instance
return redirect()->back()->withHeaders();
If you find:
{0, string} route cannot be found while reverse-routing
This error:
Please Go to system\HTTP\RedirectResponse Line no 91 :
Change:
throw HTTPException::forInvalidRedirectRoute($route);
To:
return $this->redirect(site_url('/Home'));
(dashboard after login)
The redirect statement in code igniter sends the user to the specified web page using a redirect header statement.
This statement resides in the URL helper which is loaded in the following way:
$this->load->helper('url');
The redirect function loads a local URI specified in the first parameter of the function call and built using the options specified in your config file.
The second parameter allows the developer to use different HTTP commands to perform the redirect "location" or "refresh".
According to the Code Igniter documentation: "Location is faster, but on Windows servers it can sometimes be a problem."
Example:
if ($user_logged_in === FALSE)
{
redirect('/account/login', 'refresh');
}
Original Answer: https://stackoverflow.com/a/725200/5700401
Currently I am using Codeigniter library for my project and have a custom CMS made. Which obviously password protected but before loading every controller I have a function which I run to check if session exists and admin login otherwise redirect to login page.
public function checkLoginStatus(){
if($this->session->userdata('is_admin_login') != true) {
redirect(base_url().'admin/');
}
}
Is there a way I can check this globally and don't have to load in every controller?
my solution is.
if(empty($this->session->userdata('is_admin_login') ) {
redirect(base_url().'login/');
}else{
redirect(base_url().'admin/');
}
How to restrict user not to see others people data.
for example one user data is in this url
http://example.com/abc/xyz/1
i want to stop accessing
http://example.com/abc/xyz/2
I can stop it using normal php stuff but i want to know any thing in codeigniter that does that.
No, you need to handle this using your own code in the controller.
class Abc Extends CI_Controller {
public function xyz($var) {
if($var != some_condition_based_on_user)
show_some_error();
}
}
You can check the id of the user for example. When you log in you save the id of the user into session something like this in the model on login function:
$this->session->set_userdata(array('user_id' => $user['id']);
after into your function you can check if the get value is the same of the session like:
public function xyz($id) {
if($id != $this->session->userdata('user_id')){
//code error
}
}
Im tying to use the command sequence:
Yii::app()->user->setFlash('success', "Successful!");
Yii::app()->user->logout();
$this->redirect(array('user/login'));
The user got logged out and redirected, but the Setflash does not work.
I also tried to change the order of 2 frist commands, but got the same problem.
If I do not logout the user, the Setflash works fine.
How can I make both commands work?
this should work
Yii::app()->user->logout();
Yii::app()->session->open();
Yii::app()->user->setFlash(...);
If you need to destroy a whole session but you want to set a flash afterwards, you may extends CWebUser this way:
<?php
class BaseWebUser extends CWebUser
{
public function logout($destroySession = true)
{
parent::logout($destroySession);
Yii::app()->session->open();
}
}
?>
have a closer look here
I think you can use this :
public function afterLogout() {
// Create new session
$session=new CHttpSession;
$session->open();
// Set flash message
Yii::app()->user->setFlash('success', 'You are logged out successfully.');
// Prepare target URL after logout
$continue_url = Yii::app()->request->hostInfo . Yii::app()->createUrl('');
// Redirect
CController::redirect($continue_url);
}
Put it inside your WebUser components.
Flash messages are stored in the session. Logging the user our destroys the user's current session. Once session_destroy() is called, you must call session_start() again in order to generate a new session ID and have this work. Yii most likely does not do that.
If it's that important that you have a "Successful" message indicating that the logout worked - then redirect the user to a "logout successful" page. Alternatively, you can look into overriding the way Yii performs a logout - although I wouldn't recommend it.
I'm new to CodeIgniter and I started to use the session library.
I have autoloaded the session library and trying to save the current user_id to the session userdata array. But the information is gone when I try to read it on an other page..
The native PHP sessions work just fine (tested it), so it must be something from CI.
I programmed a simple test page where I test the following:
Set the session userdata.
Test page shows the userdata correctly.
Uncomment the set session data lines in the code of the controller and reload the page.
Test page doesn't show the userdata.
The code of the controller:
class Welcome extends CI_Controller {
public function index(){
$data = null;
$data['test'] = "Yeeeeh!!";
$this->session->set_userdata($data);
$this->load->view('welcome_message', $data);
}
}
Code of the view:
<?php
echo $this->session->userdata('test');
?>
Why does the view display the session_id and not the "test" variable you created?
Did you test
<?php
echo $this->session->userdata('test');
?>
in the view file?
CI's sessions are cookies, not PHP native sessions. Calling sessions in a view works (IIRC), but since your view is loaded in the same request the session is created, it won't be set.
You need to call it on another request (i.e. another controller), or set the session somewhere else (in another controller, via AJAX could work also), or use native PHP $_SESSION array instead.
I think your actual code is just a test case, otherwise why not just
public function index(){
$data = null;
$data['test'] = "Yeeeeh!!";
$this->session->set_userdata($data);
$this->load->view('welcome_message', $data);
}
in view:
<?php
echo $test;
?>