Check session in codeigniter - codeigniter

I am new to CODEIGNITER framework and i have a problem to check whether is set session['username']
in "php" I would just do :
if( is set ($_SESSION['username'])){
$username = $_SESSION['username'];
//...more code here
} else {
//more code here
}
But i don't know how to test that in this framework.
Thanks to everyone willing to help me!

You can check this way
if($this->session->userdata('username')){
// do something when exist
}else{
// do something when doesn't exist
}

Try this
if($this->session->userdata('username')){
//enter code here
}
for setting session
$this->session->set_userdata('username','your_username');
For more info https://ellislab.com/codeIgniter/user-guide/libraries/sessions.html

If you are using Codeigniter 3 you can use the magic getters and setters method for session library.
To set a session var:
$this->session->username = 'your_username';
And to get a session var:
echo $this->session->username;

Related

Can't get Another field from session

I got problem about session data, in my web, i want to make a different view based on previledge user, here my code in controller :
$previledge = $this->session->userdata['previledge'];
$data['previledge']=$previledge;
if($data['previledge'] == 'admin'){
$this->load->view("app_admin/global/header",$d);
$this->load->view("app_admin/materi/home");
$this->load->view("app_admin/global/footer");
}
else {
$this->load->view("app_admin/global/header2",$d);
$this->load->view("app_admin/materi/home");
$this->load->view("app_admin/global/footer");
}
}
if i run my code above, previledge with admin can't go to the right view.
if there any suggestion, please inform,
thanks
Its something like syntax error.
$previledge = $this->session->userdata('previledge');
This will help you.
Below code must have to work
$this->session->userdata('previledge')=='admin'

How do i redirect to a page from php yii2.0 components?

I Have a component ,in which have one init() function which is to be called before each action.
I only need to check if the session is expired redirect the user to login.
Here is my code,
config/main.php coponents -
'MyGlobalClass'=>[
'class'=>'common\components\MyGlobalClass'
],
and
'bootstrap' => ['log','MyGlobalClass'],
components/MyGlobalClass .php :
class MyGlobalClass extends \yii\base\Component{
public function init() {
//echo "Hi";
if(Yii::$app->user->isGuest)
{
//echo 'called';exit;
Yii::$app->getResponse()->redirect(Yii::$app->urlManager->createUrl('login'));
}
//parent::init();
}
}
so it is coming inside if{} but not redirecting to login page.
You can try this, it worked for me:
return Yii::$app->getResponse()->redirect('admin/page/signin');
You may use this to send your response
Yii::$app->response->send();
but please review the guide for controller/action distinct access control
http://www.yiiframework.com/doc-2.0/guide-security-authorization.html
You can try the code below:
Yii::$app->getResponse()->redirect(Yii::$app->urlManager->createUrl('login'));
return;
correct way is :
Yii::$app->response->redirect(Yii::$app->urlManager->createAbsoluteUrl('site/logout'));
return;
This way you'll get an infinite redirect loop: The component is called on each controller call, redirection will never stop.
Better to manage it from public function behaviors() on each controller, check the Authorization section on Yii2 documentation.
May be this one help you :)
return Yii::$app->getResponse()->redirect(['user/login']);
or
return Yii::$app->getResponse()->redirect(Yii::$app->urlManager->createUrl('user/login'));

CodeIgniter Getting Not Found Image Path In Session

I'm implementing redirect to previous page after login and logout.
So in each methods of controller I've saved session like as follow.
$this->session->set_userdata('previous_page', current_url());
And after successful login and logout, I'm calling a library method as follows.
function redirect_to_previous_url() {
$url = base_url();
if($this->_CI->session->userdata('previous_page')) {
// Get previous_url
$url = $this->_CI->session->userdata('previous_page');
$this->_CI->session->unset_userdata('previous_page');
}
return $url;
}
But Its redirecting to base_url of the site. After checking the session value Its showing not found image path but not what I've saved it before.
I'm not able to find out what is the problem behind this.
Please help me to rectify and the work would be appreciated
Try this..
function redirect_to_previous_url() {
$url = base_url();
if($this->_CI->session->userdata('previous_page')) {
// Get previous_url
$url = $this->_CI->session->userdata('previous_page');
$this->_CI->session->unset_userdata('previous_page');
return $url;
}
return $url;
}
I would ensure the session was set. Like this;
if($this->_CI->session->userdata('previous_page')) {
show_error('The session is set');
}
If you don't see the error, the session isn't set. Then you know this isn't where the problem lies.
No need to store Previous URL in session.
In core php you can get previously visited URL in following server variable
$_SERVER['HTTP_REFERER'];
Same can be achieved in CodeIgniter as
$this->load->library('user_agent');
echo $this->agent->referrer();

Checking for CodeIgniter session_id to not be set

I'm trying to check if its set in my codeigniter application like:
elseif(!isset($this->session->userdata('session_id'))){ ## SESSION data is NOT set
// load a generic 'issue' occurred view.
}
but I keep getting this error, is !isset not valid in Codeigniter? How do I go about easily checking this?
Thanks
You must use the code like below:
$id = $this->session->userdata('session_id');
// your other code
elseif(!isset($id)){
// load a generic 'issue' occurred view.
}
The reason you can see here
You coud also do this ,
elseif($this->session->userdata('session_id') !== false)
{
// SESSION data is NOT set
// load a generic 'issue' occurred view.
}
Note: The function returns FALSE (boolean) if the item you are trying to access does not exist.

Magento returning incorrect customer data on frontend pages

isn't this the right method to get Name of logged in customer?
<?php echo Mage::helper('customer')->getCustomer()->getName(); ?>
I have a website with live chat functionality. Yesterday I have been asked to pass email address and the name of the logged into the user into the Javascript Tracking variable code placed in the head section of the website. So that the operators could see who is on the website and whom are they talking to without any need to ask about their information.
So I passed the information from Magento into the Javascript code but now I see this very strange thing happening. For example,
If I am logged in with credentials Name = John Email =
john12#yahoo.com
Then This name and email variable values are changing with the change of pages. For example if I click on any product page the variable values which I am passing changes to some other user's information.
Name becomes Ricky Email becomes ricky23#gmail.com
this variable values are kept on changing back to john and from john to something else with the change of pages. So operator does not have any idea whom are they talking because the values are kept on changing. Also, user ricky or who ever it changes to also exist in the database. so it is picking up random person from the database.
This is what i did to pass the code to javascript. Please let me know if that is not the right code to pass the information. Please check the php code I am using to fetch information from Magento. Roughly, I receive incorrect value once in 5 times. Please provide some assistance. Thanks in advance.
<?php
$customer = Mage::getSingleton('customer/session')->getCustomer();
$email = $customer->getEmail();
$firstname = $customer->getFirstname();
$lastname= $customer->getLastname();
$name = $firstname . ' ' . $lastname;
?>
<script type="text/javascript">
if (typeof(lpMTagConfig) == "undefined"){ lpMTagConfig = {};}
if (typeof(lpMTagConfig.visitorVar) == "undefined"){ lpMTagConfig.visitorVar = [];}
lpMTagConfig.visitorVar[lpMTagConfig.visitorVar.length] = 'Email=<?php echo $email; ?>';
lpMTagConfig.visitorVar[lpMTagConfig.visitorVar.length] = 'Name=<?php echo $name; ?>';
</script>
I'm also attaching a snap shot
I'd be interested to hear how you're adding this code to the page? Is it in it's own block, or are you adding it to footer.phtml, or similar? If your adding to an existing block be sure to check the block caching settings of that template.
To confirm the caching hypothesis I'd ask the following:
Do you get the same name, all the time, on the same page? When you refresh the page, do you get the same name and email in the Javascript?
Does the problem persist with caching disabled?
This doesn't sound like a singleton problem at all. Each execution of the PHP script is isolated from the others, serving one page request. There's no chance of another customer's object moving between invokations of the script.
It is a matter of understanding the singleton pattern. If you call your code twice:
$customer_1 = Mage::helper('customer')->getCustomer()->getName();
$customer_2 = Mage::helper('customer')->getCustomer()->getName();
you get two different instances of the object. But... if one of them has already implemented a singleton pattern in its constructor or has implemented a singleton getInstance then both objects will actually point to the same thing.
Looking at the customer/helper/Data.php code you can see the function
public function getCustomer()
{
if (empty($this->_customer)) {
$this->_customer = Mage::getSingleton('customer/session')->getCustomer();
}
return $this->_customer;
}
That means that in one of the cases singleton is already implemented/called and in other one - not as the property is already set.
The correct way to work with quote/customer/cart in order to get always the correct data is always to use the singleton pattern.
So using this:
$customer = Mage::getSingleton('customer/session')->getCustomer();
always guarantee that you get the correct customer in that session. And as may be you know singleton pattern is based on registry pattern in app/Mage.php:
public static function getSingleton($modelClass='', array $arguments=array())
{
$registryKey = '_singleton/'.$modelClass;
if (!self::registry($registryKey)) {
self::register($registryKey, self::getModel($modelClass, $arguments));
}
return self::registry($registryKey);
}
and looking at app/Mage.php:
public static function register($key, $value, $graceful = false)
{
if (isset(self::$_registry[$key])) {
if ($graceful) {
return;
}
self::throwException('Mage registry key "'.$key.'" already exists');
}
self::$_registry[$key] = $value;
}
...
public static function registry($key)
{
if (isset(self::$_registry[$key])) {
return self::$_registry[$key];
}
return null;
}
you can see that Magento checks is it is already set. If so, Magento will either throw an Exception, which is the default behavior or return null.
Hope this will help you to understand the issue you face.
I have sorted this out. I have moved the code from footer.phtml to head.phtml and it's working fine now.Values are not changing anymore. If anyone know the logic behind please post and I will change my answer. So far this is working.

Resources