passing a session variable in a function to a helper in codeigniter - php

Here's what I'm trying to do. This is the function in the controller
public function get_started()
{
if(test_login($this->session->all_userdata())) {
$this->load->view('template');
} else {
$this->load->view('error');
}
}
This is the helper
function test_login($sessdata)
{
if($sessdata->userdata('is_logged_in')) {
return true;
} else {
return false;
}
}
I have entered is_logged_in as a boolean session variable.
However, this doesn't work.
I can't find the error.

instead of passing session data as parameter to your helper, you could access the session from helper itself, like:
function test_login() {
$CI = & get_instance(); //get instance, access the CI superobject
$isLoggedIn = $CI->session->userdata('is_logged_in');
if( $isLoggedIn ) {
return TRUE;
}
return FALSE;
}
And controller:
public function get_started(){
if( test_login() ) {
$this->load->view('template');
}
else {
$this->load->view('error');
}
}

Related

Opinion about using SESSION with PHP

I need opinion about using session with php. I'm useing session to store data. For instance - configuration:
First I'm loading data from config.ini to $_SESSION['config']
Then I'm using custom session class to get specific data from $_SESSION['config'][$key];
This is config function:
public static function load_config($process_sections = FALSE)
{
$array = parse_ini_file(CONFIG . DS . 'config.ini', $process_sections);
if ($array)
{
$_SESSION['configuration'] = $array;
return TRUE;
}
else
{
$_SESSION['configuration'] = array();
return FALSE;
}
}
function config($key, $default = NULL)
{
if (isset($_SESSION['configuration']))
{
if (isset($_SESSION['configuration'][$key]))
{
return $_SESSION['configuration'][$key];
}
else
{
return $default;
}
}
}
That same is with user object. I'm getting user data not from DB, but API, and storing it in $_SESSION['user']. When user object is constructs, I'm attributing all properties just from $_SESSION['user'][...], for instance:
public function __construct()
{
parent::__construct();
$this->initUser();
}
private function initUser()
{
if (Session::is('user'))
{
return $this->setUserData(Session::get('user'));
}
else
{
return FALSE;
}
}
private function setUserData($data)
{
foreach ($data as $key => $value)
{
if(property_exists($this->_name, $key))
{
$this->{$key} = $value;
}
}
return TRUE;
}
Properties are defined in class. I'm doing it just on time, when object is constructing. Is that right practice? It's working very good for me but I doubt if my method overolads server.

codeigniter how do i pass Value after update done and redirect to Index()

how do i pass TRUE / FALSE after update done and redirect to Index() and set
condition $viewdata['show'] to append my html sucess or something
My Controller
class Description extends CI_Controller {
public function index()
{
$viewdata['content']=$this->General_model->get_page_uri();
$viewdata['show']=; //where i want to get value when update() method
//pass value so i can show sucess / error message
$this->load->view("backend/content_view",$viewdata);
}
public function update()
{
$title=$this->input->post('txttitle');
if($title != '')
{
if(!$this->update_model->update_all($title))
{
return FALSE;
}
return TRUE;
}
redirect('Admin/Description');
}
}
My Model
public function update_all($data)
{
$this->db->set('desc',$data)
->where('desc_id','1');
if(!$this->db->update('tbl_desc'))
{
return FALSE;
}
return TRUE;
}
#Ritesh d joshi thz it work but i face problem that i can't modify when update error i test to change my field name to other to test return false;
Admin/Description/update
it show me 'A Database Error Occurred' by Codeigniter
i don't want this to show i want to keep my Admin page still same just alert nomol message error that i have set not to show many info error. how could i prevent this or this can be done by Ajax request only ?
Controller index()
if($show_ses === '0')
{
$viewdata_result = $this->General_model->rk_alert_ok('Successfully Update');
$this->session->set_flashdata('show', 'false');
}elseif($show_ses === '1'){
$viewdata_result=$this->General_model->rk_alert_no('Fail Update Request');
$this->session->set_flashdata('show', '');
}
Controller update()
if(!$this->update_model->update_all($title))
{
$this->session->set_flashdata('show', '1');
//1= false
}else{
$this->session->set_flashdata('show', '0');
//0=true
}
Use the PHP header() function.
header('Location: your_URL');
Update:
In CI, you can use redirect() function, this document will help you to understand: http://www.codeigniter.com/user_guide/helpers/url_helper.html
Please try this
class Description extends CI_Controller {
public function index()
{
$viewdata['content']=$this->General_model->get_page_uri();
$show= $this->session->flashdata('show');
if($show){
// Here is code for show and message
$viewdata['show']="message";
$this->session->set_flashdata('show', 'false');
}
$this->load->view("backend/content_view",$viewdata);
}
public function update()
{
$title=$this->input->post('txttitle');
if($title != '')
{
if(!$this->update_model->update_all($title))
{
return FALSE;
}
$this->session->set_flashdata('show', 'true');
return TRUE;
}
redirect('Admin/Description');
}
}
You can use redirection in update() as:
public function update()
{
$title = $this->input->post('txttitle');
if($title != '')
{
$status = $this->update_model->update_all($title);
if($status){
redirect(base_url().'index?show=1');
}
else{
redirect(base_url().'index?show=0');
}
}
redirect('Admin/Description');
}
than you can check the status in index() as:
public function index()
{
$viewdata['content']=$this->General_model->get_page_uri();
if(isset($this->input->post('show')) && intval($this->input->post('show')) == 0){
$viewdata['show'] = 1; // if success than show 1
}
else{
$viewdata['show'] = 0; // if error than show 0
}
$this->load->view("backend/content_view",$viewdata);
}
You can use the Header function, and to detect it you can pass the parameters too in the GET Url like below.
By default set the status as FALSE. ANd you can update the status according to your conditions either to FALSE or TRUE.
public function update()
{
$status = false;
$title=$this->input->post('txttitle');
if($title != '')
{
if(!$this->update_model->update_all($title))
{
$status = FALSE;
return FALSE;
}
$this->session->set_flashdata('show', 'true');
$status = TRUE;
return TRUE;
}
header('Location: abc.php?status='.$status);
}
Hope This will work, Do let me know in case of any confusion.

Serializable objects disappearing from session, but not on localhost

I have a shopping cart object that implements serializable, and it works fine on my localhost, but when I upload it to the live server it stops working correctly.
When I add a product to the shopping cart and print_r($_SESSION) I can see the products have been added successfully, but when I refresh the page they disappear. This only happens with objects that implement serializable. These same objects work perfectly on my localhost, which has IDENTICAL code, and it's driving me insane.
Could it be a difference in session handling between php version 5.5 and 5.6?
I am using spl_autoload_register to load my classes if that helps at all (none of them appear in the session as incomplete_class or anything like that).
I also noticed that the session save path is blank on the live version, but is set on my localhost - but the rest of the session functions perfectly - it's only when it contains serializable classes that everything disappears.
Please help before I murder someone...
OK here's the code:
shopping cart class:
class shoppingCart implements Serializable
{
private $products, $error;
function __construct()
{
}
function addProduct($productCode, $quantity = 1)
{
include_once ('include/requests.php');
$productInfo = requestPostData('getProductList');
if (in_array(strtoupper($productCode), $productInfo['results']) == true)
{
if (isset($this->products[strtoupper($productCode)]))
{
$this->products[strtoupper($productCode)] = $this->products[strtoupper($productCode)] + $quantity;
return true;
}
else
{
$this->products[strtoupper($productCode)] = $quantity;
return true;
}
}
else
{
$this->error = 'Product '.$productCode.' could not be found.';
}
}
function editProduct($productCode, $quantity)
{
if (isset($this->products[strtoupper($productCode)]))
{
$this->products[strtoupper($productCode)] = $quantity;
}
}
function removeProduct($productCode)
{
if (isset($this->products[strtoupper($productCode)]))
{
unset($this->products[strtoupper($productCode)]);
}
}
public function getProducts()
{
if (count($this->products) >= 1)
{
return $this->products;
}
else
{
return false;
}
}
public function isInCart($productCode)
{
if (isset($this->products[strtoupper($productCode)]))
{
return true;
}
else
{
return false;
}
}
public function getQuantity($productCode)
{
if (isset($this->products[strtoupper($productCode)]))
{
return $this->products[strtoupper($productCode)];
}
else
{
return 0;
}
}
public function getError()
{
$error = $this->error;
return $error;
}
public function resetError()
{
$this->error = '';
}
public function serialize()
{
$dataArray = array('products' => $this->products, 'error' => $this->error);
return serialize($dataArray);
}
public function unserialize($data)
{
$dataArray = unserialize($data);
$this->products = $dataArray['products'];
$this->error = $dataArray['error'];
}
}
And the code on the page:
if (session_status() !== PHP_SESSION_ACTIVE)
{
session_start();
}
if (!isset($_SESSION['shoppingCart']))
{
$_SESSION['shoppingCart'] = new shoppingCart;
}
if (isset($_POST['cart__add_to_cart']))
{
if (isset($_POST['cart__quantity']))
{
if ($_SESSION['shoppingCart']->addProduct($_POST['cart__add_to_cart'], $_POST['cart__quantity']))
{
header('Location: http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
}
}
else
{
if ($_SESSION['shoppingCart']->addProduct($_POST['cart__add_to_cart']))
{
header('Location: http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
}
}
}
If I print_r($_SESSION) right at the bottom of the page after a product has been added then it appears in the session as it should... But as soon as I refresh it disappears :'(

Can't use function return value in write context

I have this simple session class
class Session
{
public static function init() {
#session_start();
}
public static function set($key, $value) {
$_SESSION[$key] = $value;
}
public static function get($key) {
if (isset($_SESSION[$key]))
return $_SESSION[$key];
}
public static function destroy() {
unset($_SESSION);
session_destroy();
}
}
In my other class I have
public function verifyFormToken($form)
{
// check if a session is started and a token is transmitted, if not return an error
if(!isset(Session::get($form.'_token'))){
return false;
}
// check if the form is sent with token in it
if(!isset($data['token'])) {
return false;
}
// compare the tokens against each other if they are still the same
if (Session::get($form.'_token') !== $data['token']) {
return false;
}
return true;
}
I can set a session no problem but when I come to get it using verifyFormToken(), i get this error message
Can't use function return value in write context
which points to this line
if(!isset(Session::get($form.'_token'))){
you will have to define a variable as pass that to isset:
$token = Session::get($form.'_token');
if ($token !== NULL) { ... }
or as you are using isset in your get method just do:
if (Session::get($form.'_token') !== NULL) { ... }
EDIT**
In this instance this would be fine, as session token will never be null, but as a session controller, a value may be set as NULL on purpose, or may not be set, so your get method needs to return a unique value to determine whether its set or not. i.e.
define('MY_SESSION_NOT_SET',md5('value_not_set'));
class Session
{
public static function init() {
#session_start();
}
public static function set($key, $value) {
$_SESSION[$key] = $value;
}
public static function get($key) {
if (isset($_SESSION[$key]))
return $_SESSION[$key];
else
return MY_SESSION_NOT_SET;
}
public static function destroy() {
unset($_SESSION);
session_destroy();
}
}
if (Session::get($form.'_token') === MY_SESSION_NOT_SET) { ... }
something like that would be more beneficial.

Manipulating passed arguments in php

Im not so experienced in php , Im using codeigniter to write my application , I have my own library and within my library there are three functions/methods that passes there arguments in one function which is in one of my models , my question is how will i manipulate/trick the method in my model to know exactly which function among the three in my library has passed the value and return the correct value ..
1st function
public function id_exist ($id) {
if(empty($id)) {
return FALSE;
}
return $this->library_model->this_exist($id);
}
2nd function
public function group_exist($group) {
if(empty($group)){
return FALSE;
}
return $this->library_model->this_exist($group);
}
with the 3rd same as the above 2
in my model
public function this_exist ($item) {
if(empty($item) || !isset($item)) {
return FALSE;
}
// here is where i need to know which function has passed the argument so that i can work with it and return the correct value from the database
}
Might be dirty, might be not sophisticated, but why not passing another argument which tells exactly the origin?
public function id_exist ($id) {
if(empty($id)) {
return FALSE;
}
return $this->library_model->this_exist('id', $id);
}
public function group_exist($group) {
if(empty($group)){
return FALSE;
}
return $this->library_model->this_exist('group', $group);
}
Model:
public function this_exist ($origin, $item) {
if(empty($item) || !isset($item)) {
return FALSE;
}
if($origin == 'id'){
// do something
}
elseif($origin == 'group') {
// do something else
}
}

Categories