CodeIgniter, set_flashdata not working after redirect - codeigniter

set_flashdata is not working directly after redirect with only one redirect.
I am using one controller in this process - Profilers' Controller. It handles the member confirmation process and also displays the login page on the redirect. The process is as follows:
this session set_flashdata ('topic', 'newmember')
redirect ('login')
route ['login'] = 'profilers/signIn'
topic = $this session flashdata ('topic')
I have turned off all database session configuration for cleaner debugging and even though session library is turned on in configs, I have started calling it anyways which doesn't seem to work either.
Here is my code. As you can see, I am sending path info to a log file path.log:
in controller Profilers, function confirmMember:
public function confirmMember()
{
//use_ssl();
$this->form_validation->set_rules('handle', 'Unique Member Name', 'trim|xss_clean|required|min_length[5]|max_length[30]');
$this->form_validation->set_rules('confirmation', 'Confirmation Code', 'trim|xss_clean|required|min_length[20]|max_length[20]|alpha_numeric');
if ($this->form_validation->run() === FALSE) {echo "here";exit;
$data['handle']=$this->input->post('handle');
$data['confirmation']=$this->input->post('confirmation');
$this->load->view('signing/defaults/header',$data);
$this->load->view('defaults/heading',$data);
$this->load->view('defaults/banner');
$this->load->view('defaults/banner_right');
$this->load->view('member/temp/index',$data);
$this->load->view('defaults/footer',$data);
} else {
$post = $this->input->post(NULL,TRUE);
$data['member'] = $this->Signing_model->model_confirmMember($post);
if ($data['member']['confirmed']!==FALSE) {
/* PATH CHECK */
error_log("member confirmation not false\n",3, LOG_DIR.'path.log');
unset($post);
$this->session->sess_destroy();
$this->session->set_flashdata('topic', 'newmember');
// $this->session->keep_flashdata('topic');
redirect('login','refresh');
} else {
/* PATH CHECK */
error_log("member confirmation IS FALSE\n",3, LOG_DIR.'path.log');
$this->load->view('member/temp/index',$data);
}
My log file shows that the path is using the correct path and showing "member confirmation not false".
I have tried with keep_flash data on (which I assumed wouldn't work since there are no other redirects) and off.
I have also tried redirect without 'refresh'.
In config/routes.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$route['join'] = 'profilers/joinUp';
$route['login'] = 'profilers/signIn';
...
Login page uses Profilers Controller, signIn function as show above:
public function signIn()
{
$topic = $this->session->flashdata('topic');
if (isset($topic)) {
$message = "topic is set. topic = ".$topic."\n";
if ($topic!==FALSE) {
error_log("flash var topic is not false\n", 3, LOG_DIR.'path.log');
} else {
error_log("flash var topic is FALSE\n", 3, LOG_DIR.'path.log');
}
} else {
$message = "topic is NOT set\n";
}
error_log($message,3,LOG_DIR.'path.log');
exit;
...
...
}
log file is showing that topic is set but is false.
"flash var topic is FALSE"
"topic is set. topic = "
Of course topic var not set since it is FALSE.
As you can see, I have moved the get flash data function to the beginning of my controller function to bypass anything that may be corrupting data.

You may need to start the session again after you have destroyed it.
Try adding this after your call to sess_destory():
$this->session->sess_create()
Alternatively you could avoid destroying the session, and unset() the values you wish to get rid of.

Related

How to redirect to the method of a controller after user doing authentication on codeigniter?

I am using the Default Controller to make the user authentication. What I am trying to do is whatever is the page the user request news/add or news/index or themes/all or maps/view, if he is not logged in, he or she will be directed to the log in page and then redirected to the page he wanted to go, not always the same page.
You can your the
CodeIgniter User Agent Library and Session Library to store and use the referring url. The user agent library is basicly accessing the $_SERVER['HTTP_REFERER'] value.
NOTE: from the php.net website:
Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
so this is not a foolproof method.
if ($this->agent->is_referral()) {
$this->session->set_userdata('prev_url', $this->agent->referrer());
}
// later, when login is successful
$prev_url = $this->session->userdata('prev_url');
if( $prev_url ) {
redirect($prev_url);
}
one way is to do it in the constructor of your controller. that way they are redirected before going to the news/add etc.
so for example you create a model called "sentry" and a "getUser()" method to check the browser cookie to see if the user is authorized. if they are not authorized have it return false. if they are authorized have it return $user so then you have it available for your other methods.
function __construct() {
parent::__construct();
$this->load->model( 'sentry' );
if ( ! $this->user = $this->sentry->_getUser() )
{ redirect( '/login/', 'refresh' ); }
}
so then for example you could have $this->user->name etc etc available to any method in the controller. And $this->user will also automatically be available in all the view files of this controller.
I do this by extending my controller and I check in constructor if person is logged in or not, if person is logged in I save to the session current URL, and redirect person to the login page (if same constructor is applied (controller one) I make exception to not save current URL to the session) after logging in I call redirect function to the session variable.
How to extend your controller is done here http://philsturgeon.co.uk/blog/2010/02/CodeIgniter-Base-Classes-Keeping-it-DRY
note that when your controller is extended you use $this->data['variable_sent_to_view'] and you can omit second parameter of $this->load->view()
here is some example code assuming you know how your login controller works
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->output->enable_profiler(FALSE);
if ($refer = $this->session->flashdata('refer')) {
$this->data['refer_page'] = $refer; // $this->data['refer_page'] is variable that you are interested in
unset($refer);
} else {
$this->data['refer_page'] = base_url(); //default refer_page
}
//check if user is NOT logged in
if (!$logged_in) {
$this->_setRefer(); //this is private function
}
// else dont care about it
}
private function _setRefer() {
$invalid_method = array('search', 'login'); // if method is 'search' or 'login' url will not save in session (it will stay same as was before)
$valid_refer = TRUE;
if (in_array($this->router->method, $invalid_method)) {
$valid_refer = FALSE;
}
if (!(count($_POST) > 0) && $valid_refer === TRUE && !$this->input->is_ajax_request()) {
$this->session->set_flashdata('refer', current_url());
} else {
$this->session->set_flashdata('refer', $this->data['refer_page']);
}
}
}
now in after succesful login redirect to $this->data['refer_page'], but note that login controller must by extended by MY_Controller.
this script also takes care about what happens if user made mistake and inserted wrong password (page will reload but "old" url stays)

PHP - Global Variables

I am trying to dynamically set database connection credentials based on who logs into a web page. I'm pretty sure it's not working because of the $connectdb variable not being defined. Can someone please check out my code and try to get it working? Thanks!
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$connectdb="";
class Main extends CI_Controller {
function __construct() {
parent::__construct();
echo $connectdb;
$this->load->database($connectdb);
$this->load->helper('url');
$this->load->library('grocery_CRUD');
}
public function index() {
if ($_POST["username"] == "root") {
global $connectdb="default";
}
if ($_POST["username"] == "user1") {
global $connectdb="user1";
}
if ($_POST["username"] == "user2") {
global $connectdb="user2";
}
$connect = #mysql_connect("localhost", $_POST["username"], $_POST["password"]);//won't display the warning if any.
if (!$connect) {
echo 'Server error. Please try again sometime. CON';
} else {
print("Employees");
echo "<br>";
print("Visitors");
}//Just an example to ensure that we get into the function
// LOAD LIBRARIES
}
public function employees() {
$this->grocery_crud->set_table('employees');
$output = $this->grocery_crud->render();
$this->_example_output($output);
}
public function visitors() {
$this->grocery_crud->set_table('visitors');
$output = $this->grocery_crud->render();
$this->_example_output($output);
}
function _example_output($output = null) {
$this->load->view('our_template.php',$output);
}
}
A quick read of THE MANUAL will show you it's pretty easy to have multiple database connections. You define the connection parameters in your database.php config file then call the database with the group name.
if($user == 'someguise'){
$this->load->database('guiseDB');
}
HTH
For something as important as this i would strongly suggest running the form input through CI form validation first. You really should be validating and doing things like limit the number of characters, make sure its letters only, trim whitespace and XSS cleaning - all before you do anything else. (this helps your user as well)
then to get the value from the form - do something like this
$username = $this->input->post( 'username', TRUE ) ;
and work with the one variable $username. the TRUE XSS cleans the value, and then instead of repeating
$_POST["username"] ==
over and over and over, you are just checking $username. also makes the code easier to read. if you need $username in different methods just use:
$this->username = $this->input->post( 'username', TRUE ) ;
and then $this->username will work in any method in the class.
finally consider having a table of users or config list -- and then use a different value to call your database. in other words maybe they log in with the user name: "root" but then its a different name like global $connectdb = "rootadmin"

change any rule in codeigniter to match function

I have set up my routes.php to suit the nature of my site. Unfortunately, there is a problem with my last route i.e.:
$route['(:any)'] = "profile/profile_guest/$1";
If the username password name passed is correct, for e.g. domain.com/username, it will load his/her data. if not, it loads the page with errors (because failure to retrieve data with non-existent user in database). This is my problem! I want to avoid this error showing.
Is there anyway I could avoid this error from happening? None of the echoes seems to be printing or the redirect neither is working. Don't know why! it is as if the code inside this method is not executing and the view is loaded instead. below is part of the profile_guest function:
public function profile_guest($username)
{
$username = $this->uri->segment(1);
//echo "Hello " . $username;
redirect('main', 'refresh');
if($username != '')
{
/* echo "<h1>HELLO WORLD SOMETHING</h1>"; */
It's hard to say without seeing the rest of the code.
Maybe you need to check the value before running the query:
// user_model
function get_user($username = NULL){
if($username){
return $this->db->query(...
}else{
return false;
}
}
Then check that the query returned anything before loading the view
if($this->user_model->get_user($username){
//show the page
}else{
echo "no user found";
}

How can I trigger controllerless core Magento modules that watch <controller_action_predispatch> in <frontend> in config.xml from external script

For background reference
SEE: Magento: How do I get observers to work in an external script?
I wanted to ask what the preferred method to 'replicate' a frontend controller's action from an external script is. I am creating an external SSO login for Magento EE 1.12.
My code exists as the following in a php file. You can test it by creating test.php and replacing my user (185) with whatever your user ID is. Navigate to the page and then again. You will notice you are logged in and out, however in admin it will not show you as being online. Read on...
<?php
umask(0);
require_once 'app/Mage.php';
Mage::app("default");
// Set the session to frontend according to many suggestions
Mage::getSingleton("core/session", array("name" => "frontend"));
// Alan Storm suggestion to load specific area in Magento (frontend)
Mage::app()->loadArea(Mage_Core_Model_App_Area::AREA_FRONTEND);
// Load My Specific User
$user = Mage::getModel('customer/customer')->load(185)->setWebsiteId(Mage::app()->getStore()->getWebsiteId());
// Get the session object
$session = Mage::getSingleton('customer/session');
// Make it look good for debugging
echo "<PRE>";
// Toggle the customer logged in / logged out upon page load
if ($session->isLoggedIn())
{
try
{
$session->session->setCustomer($user);
echo "LOGGED IN<br>";
var_dump($session->getCustomer()->getIsJustConfirmed());
} catch (Mage_Core_Exception $e) {
$message = $e->getMessage();
var_dump($message);
}
} else {
$session->logout();
}
var_dump($session->getCustomer());
echo $session->isLoggedIn() ? $user->getName().' is online!' : 'not logged in';
?>
This code logs in the user, however none of the Mage_Log, Mage_Persistent, or any other module without a controller that relies on the controller_action_predispatch and controller_action_postdispatch event attached to the frontend area in config.xml will ever fire.
Mage_Log is a perfect example of this situation where it watches customer_login and fires the bindCustomerLogin() function (since I'm using Alan Storm's suggestion above) but the controller dispatch does not fire, resulting in failure of the module to work properly.
How can these other modules ever possibly be triggered from an external script (or a global observer watching the controller_front_init_routers event)?
EDIT: SOLUTION
Here is the final results from the suggestions by benmarks above... I am emulating the Mage_Customer controller. The script below demonstrates how to perform a COMPLETE magento login. It is not extensively tested, but it does show the user as being logged in in the backend. It is the most complete solution i've seen to date.
public function autoMageLogin() {
// Include the controller itself so the object can be used
include ('/var/www/app/code/core/Mage/Customer/controllers/AccountController.php');
// Configure Magento to think its using the frontend
Mage::getSingleton("core/session", array("name" => "frontend"));
Mage::getConfig()->init();
Mage::getConfig()->loadEventObservers('frontend');
Mage::app()->addEventArea('frontend');
Mage::app()->loadArea(Mage_Core_Model_App_Area::AREA_FRONTEND);
// Prepare the request as if it were coming from the specific
// controller (I've chosed Mage_Customer as my chosen controller
// to 'emulate' in php code
$request = Mage::app()->getRequest();
$request->setRouteName('customer');
$request->setControllerModule('Mage_Customer');
$request->setRoutingInfo('');
$request->setModuleName('customer');
$request->setControllerName('account');
$request->setModuleKey('module');
$request->setControllerKey('account');
$request->setActionName('loginPost');
$request->setActionKey('action');
$response = Mage::app()->getResponse();
// Instantiate a new AccountController object using the modified request
// and the modified response (see the include() above)
$accountControl = new Mage_Customer_AccountController($request, $response);
// Dispatch events associated to the controller
Mage::dispatchEvent('controller_action_predispatch', array('controller_action' => $accountControl));
Mage::dispatchEvent('controller_action_predispatch_customer', array('controller_action' => $accountControl));
Mage::dispatchEvent('controller_action_predispatch_customer_account_loginPost', array('controller_action' => $accountControl));
// Load the current user
$user = Mage::getModel('customer/customer')->load(185)->setWebsiteId(Mage::app()->getStore()->getWebsiteId());
// Grab the current session
$session = Mage::getSingleton('customer/session');
// From this point forward, emulate the controller actions
if (!$session->isLoggedIn()){
try{
$session->setCustomerAsLoggedIn($user);
$session->renewSession();
echo "LOGGED IN<br>";
} catch (Mage_Core_Exception $e) {
$message = $e->getMessage();
var_dump($message);
}
} else {
echo "LOGGED OUT<br>";
$session->logout();
}
// Now fire the post controller action events
Mage::dispatchEvent('controller_action_postdispatch_customer_account_loginPost', array('controller_action'=>$accountControl));
Mage::dispatchEvent('controller_action_postdispatch_customer', array('controller_action'=>$accountControl));
Mage::dispatchEvent('controller_action_postdispatch', array('controller_action'=>$accountControl));
// log to the screen and be done
var_dump($session->getCustomer());
echo $session->isLoggedIn() ? $session->getCustomer()->getName().' is online!' : 'not logged in';
die();
}
You will need to manually dispatch the events with the original params e.g.
Mage::dispatchEvent(
'controller_action_predispatch',
array('controller_action',Mage::app()->getRequest()
);
See Mage_Core_Controller_Varien_Action::preDispatch() (link) for more info. Note that the pre- and post-dispatch methods dispatch dynamic events based on routename params which may or may not be a concern.
If you rewrite the external script as a custom controller and action then all the events will fire naturally. However, you must have a reason for making it external in the first place.

CodeIgniter - showing original URL of index function?

I'm not sure if I'm approaching this fundamentally wrong or if I'm just missing something.
I have a controller and within it an index function that is, obviously, the default loaded when that controller is called:
function index($showMessage = false) {
$currentEmployee = $this->getCurrentEmployee();
$data['currentEmp'] = $currentEmployee;
$data['callList'] = $currentEmployee->getDirectReports();
$data['showMessage'] = $showMessage;
$this->load->view('main', $data);
}
I have another function within that controller that does a bulk update. After the updates are complete, I want the original page to show again with the message showing, so I tried this:
/**
* Will save all employee information and return to the call sheet page
*/
function bulkSave() {
//update each employee
for ($x = 0; $x < sizeof($_POST['id']); $x++) {
$success = Employee::updateEmployeeManualData($_POST['id'][$x], $_POST['ext'][$x], $_POST['pager'][$x], $_POST['cell'][$x], $_POST['other'][$x], $_POST['notes'][$x]);
}
$this->index($success);
}
What is happening is that the original page is accessed using:
localhost/myApp/myController
after the bulk update it is showing as:
localhost/myApp/myController/bulkSave
when I really want it to show the url as the index page again, meaning that the user never really sees the /bulkSave portion of the URL. This would also mean that if the user were to refresh the page it would call the index() function in the controller and not the bulkSave() function.
Thanks in advance.
Is this possible?
You are calling your index() funciton directly, within bulkUpdate() hence the uri does not change back to index because you are not making a new server request, you are just navigating within your controller class.
I usually use the same Controller function for tasks like this, directing traffic based on whether or not $_POST data has been passed or not like this...
function index() {
if($_POST) {
//process posted data
for ($x = 0; $x < sizeof($_POST['id']); $x++) {
$data['showMessage'] = Employee::updateEmployeeManualData($_POST['id'][$x], $_POST['ext'][$x], $_POST['pager'][$x], $_POST['cell'][$x], $_POST['other'][$x], $_POST['notes'][$x]);
}
}
else {
//show page normally
$data['showMessage'] = FALSE;
}
//continue to load page
$currentEmployee = $this->getCurrentEmployee();
$data['currentEmp'] = $currentEmployee;
$data['callList'] = $currentEmployee->getDirectReports();
$this->load->view('main', $data);
}
Then if it is a form that you are submitting, just point the form at itself in your view like this...
<?= form_open($this->uri->uri_string()) ?>
This points the form back at index, and because you are posting form data via $_POST it will process the data.
I usually do a redirect to the previous page as it prevent users to refresh (and submit twice) their data.
You can use the redirect() helper function of CI.
http://codeigniter.com/user_guide/helpers/url_helper.html (at the bottom)

Resources