Session variables not resetting - php

I'm having trouble resetting session variables in PHP. I'm now trying just testing resetting the session variable like this, but this doesn't even work:
session_start();
$_SESSION["name"] =false;
if (!isset($_SESSION["name"])) {
$message = getname(); //can't get this to ever be called
} else {
$message = welcome();
}
What am I missing here?

You want to unset the session variable
unset($_SESSION['name']);
Setting it to false makes it so it's still set (so isset will still return true), the only difference is that the actual value of the variable has changed to false.

Related

CodeIgniter session holds value 1 instead of true

In my codeigniter application I have specified a session as below
$this->session->isLoggedIn = true;
echo "Session";
echo $this->session->isLoggedIn;
even though I assign true the output shows as 1 instead. What have I done wrong here?
would really appreciate some help
EDIT :- The problem was actually in the following
When I try to acess this session from another method the session value is set to null. My other function is defined as
public function isLoggedIn()
{
var_dump($this->session->isLoggedIn);
if ((isset($this->session->isLoggedIn)=="true"))
{
return "true";
}
else
{
return "Sorry,false";
}
}
the vardump that I am printing in this isLoggedIn function is Null even though the session variable was assigned as displayed in the initial code above

Can not log out correctly PHP

I can log in and access all member pages, but when I log out, I can still access all memberspages
I use this code to log out:
$_SESSION["admin_id"] = false;
$_SESSION["username"] = null;
redirect_to("login.php");
and this code to check if a user is logged in,
function logged_in() {
return isset($_SESSION["admin_id"]);
}
function confirm_logged_in($page) {
if (!logged_in()) {
redirect_to($page);
}
}
he redirects me after i have used the log out code. But i can still type in the member page URL and access them like I am logged in. I use an other webbrowser its impossible, so the pages are protected correctly. Or do I need to destroy the cookie and session complectly?
Here's what you're doing when you logout.
You are setting admin_id to false (which is technically a value).
$_SESSION["admin_id"] = false;
You then check to see whether admin_id is set:
isset($_SESSION['admin_id'); // returns TRUE because it "IS SET" to false
Options
You can either check whether admin_id is not empty (which handles null, false, 0).
function logged_in() {
return ! empty($_SESSION["admin_id"]);
}
You can extend your current function.
function logged_in() {
return isset($_SESSION["admin_id"] && $_SESSION["admin_id"] !== false);
}
You can set the variable to null.
$_SESSION['admin_id'] = null;
You can destroy the session completely.
session_destroy();
In place of:
$_SESSION["admin_id"] = false;
Try this:
unset($_SESSION["admin_id"]);
If you really need to log out, in my opinion your best option is to invalidate the session with a simple session_destroy().
By doing this you can check $_SESSION with the isset() function without problems, since every parameter belonging to the old session has been unset.

How to Hide URL parameters with php redirect

I read this article: http://smallbusiness.chron.com/hiding-url-parameters-php-redirect-33163.html
which explains how to but I'm don't understand how you redirect with the header as they say in there.
For storing in sessions this is code I use
session_start();
function input_val($key, $remember = true) { //use input_val('nameofinputfield')as value to be able to store in session
$value='';
if(isset($_REQUEST[$key])) {
$value = $_REQUEST[$key];
//Store value in session if remember = true
if($remember) {
$_SESSION[$key] = $value;
}
return $value;
} else {
//Return session data
return isset($_SESSION[$key]) ? $_SESSION[$key] : $value;
}
}
Let's say, you want to pass a username and email parameter from your script1.php to script2.php. If you are using POST method, in the URL the parameters won't show, and you can access your passed variables through $_POST global variable. But, if you want to use GET method for any reason, or you want to store data in $_SESSION you can do this.
You can try to use this in your script2.php:
session_start();
if (count($_GET)) {
foreach ($_GET as $key => $value) {
$_SESSION[$key] = $value;
}
header("Location: " . $_SERVER["PHP_SELF"]);
}
//At here, you can access all of your parameters from $_SESSOION variable
var_dump($_SESSION);
I will try to explain it as simple as I can, it's not that difficult.
When a user is in a session with the php he stores a little blob of text in the browser, this text is like a user ID that lasts until he close his browser. The php script can tell and extract information from the server, like parameters, by knowing his ID. This is not a cross-server feature though and it isn't persistent, unlike cookies, the expiration on the sessions are normally short and they expire when the user closes his browser.
Also it is recommended not to use it to store Get information like Page number, because it can't be re-referenced.

Close session without writing or destroying it

Is there a way to close a PHP session without either writing or destroying it? Am I missing something or are there just two functions (session_write_close() and session_destroy()) which reset session_status() to PHP_SESSION_NONE? In other words, if I have an open session, can I simply close it without affecting the external session data, so it can be reloaded again.
You can do this by $_SESSION = null. The session is unavailable but the data remains (does not get deleted).
Consider you have data in the session:
<?php
session_start();
session_regenerate_id(); // get a fresh id
echo session_id();
$_SESSION['test'] = '12345';
print_r($_SESSION); // echoes the data in the session
Data: test|s:5:"12345";
Then in the next request:
<?php
session_start();
echo session_id() . "<br>"; // echoes the same id as of the last request
$_SESSION = null;
print_r($_SESSION); // echoes nothing
echo "<br>";
echo session_status(); // echoes 2 (PHP_SESSION_ACTIVE)
Data still the same: test|s:5:"12345";
(php-fpm 5.4.29, most recent nginx, memcached as session handler).
Well the data still can be written through $_SESSION['whatever'] = ... but not read. I'm not sure whether this is a good solution but I have to admit I still don't understand why or whatfor you need this.
As an alternative, you could implement a wrapper class for the session with a property $this->active = true; // or false:
class MySessionWrapper {
protected $active;
protected $data;
// getter setter for $this->active and $this->data ...
public function getData($var) {
if ($this->active !== true) {
throw new Exception('session disabled');
}
}
}
Some months later after raising an issue the two new methods are now available in PHP 5.6, but the documentation arrived only with 5.6.2.
session_abort() – Discard session array changes and finish session, see the docs.
session_reset() – Re-initialize session array with original values, see the docs.

cookie won't set

This is a question regarding an old one of mine: cookie won't unset:
cookie wont unset
where I had problems unseting the cookie (but it was set 'properly'),
Now that the problem is solved; the cookie doesn't seem to SET
cookie 'set': (does not work)
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
cookie check: (seems to work)
function sesion(){
if(isset($_COOKIE['id']) && isset($_COOKIE['alias'])){
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
return true; //THIS IS NEVER RETURNING TRUE
}
if(isset($_SESSION['id']) && isset($_SESSION['logueado']) && $_SESSION['logueado'] == true){
return true;
}
else{ return false;
}
}
cookie unset: (works)
function cerrar_sesion(){
session_start();
$_SESSION['logueado']= false;
$_SESSION['id']= NULL;
session_unset();
session_destroy();
setcookie("id",false,time()-3600,"/");
setcookie("alias",false,time()-3600,"/");
unset($_COOKIE['id']);
unset($_COOKIE['alias']);
}
What happens is that login is working only through $_SESSION so after 30 minutes of no activity the user is no longer logged in,
Any idea what I'm doing wrong? Thanks a lot!
As stated above you cannot read a cookie from the same page as it is set. I see you have tried tricking this using ajax but i do not believe that would be a valid trick as Ajax calls do not change the state of the page you are still on. so you can either do a full refresh or redirect OR at the same time you use setcookie you can also define the values you need in $_COOKIE so its available on the same page. like this:
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
$_COOKIE['id'] = $data['id'];
$_COOKIE['alias'] = $data['nombre'];
set cookie lines work fine with me.
as for }else if(isset($_COOKIE['id']) && i
since you return if you remove the else here is still okay, if there was no return above you would have to keep the else here in order not to evaluate this block
generally speaking I am not sure that elseif is the same with else if in all cases
The way the function session is build will act like this:
On the first load it will show: no cookie, no session because you cannot see a cookie until reload (which I guess you already know).
-On second load you will see cookie alive session set.
-after the second load you always see session is set.
All I want to say that session works exactly as expected to work, so I don't really see any problem.
<?php
$data='Hello';
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
session_start();
function sesion()
{
if(isset($_SESSION['id']) && isset($_SESSION['logueado'])
&& $_SESSION['logueado'] == true)
{
echo 'SESSION IS SET<br>';
return true;
}
if(isset($_COOKIE['id']) && isset($_COOKIE['alias']))
{
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
echo 'COOKIE is alive and session set'.$_SESSION['alias'].'<br>';
return true; //THIS IS NEVER RETURNING TRUE
}
else
{
echo 'NO SESSION, NO COOKIE YET, WAIT UNTIL REFRESH<br>';
return false;
}
}
sesion() ;
?>
Try removing the path parameter from your setcookie() calls, maybe that's the issue.
Also, did you check that $data actually contains any data?
Propably you have really known problem with setting cookies and you have disabled error reporting about warnings.
Just try:
error_reporting(E_ALL);
You will propably see at your page something like "Cannot modify headers. Headers already sent". That because you need to SET cookies before you display anything on your page. So solution to resolve your problem is to implement your code to SET cookies at the bottom of your page or use ob_start/ob_clean.
Let me know if it helps :)
According to the "setcookie()" implementation in PHP, the cookie value check will not work until you move the control from the page that you are creating the cookie. So, your "SET" will create the cookie in one page and "sesion()" should be called from other page to check the value of the cookie that you set. Try it and hope it helps!
Try the following approach (please refine this as per your need). What I am trying here to refresh the page itself after setting the cookie and the "sesion()" function is a dynamic function that may or may not have any arguments. So, when you pass any argument to it, the the cookie will be set, otherwise it will be checked for existence. An accompanying function with func_num_args() is func_get_args(). It will help you to sanitize the expected arguments in the function.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
ini_set("log_errors", 0);
session_start();
function sesion(){
// func_num_args() number of arguments passed to the function
if (func_num_args() == 0) { // if no arguments were passed, means the page is refreshed and cookie won't be set further
if(isset($_COOKIE['id']) && isset($_COOKIE['alias'])){
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
return true; //THIS IS NEVER RETURNING TRUE
}
if(isset($_SESSION['id']) && isset($_SESSION['logueado']) && $_SESSION['logueado'] == true){
return true;
}
else {
return false;
}
}
else { // if number of args > 0, means you need to cookie here and refresh the page itself
global $data; // set this to global as the $data will be available outside of this function
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
/**
* refresh the page by javascript instead of header()
* as header already being sent by the session_start()
*/
echo '<script language="javascript">
<!--
window.location.replace("' . $_SERVER['PHP_SELF'] . '");
//-->
</script>';
die();
}
}
sesion(1); // passed an argument to set the cookie
?>
I think you will face issue with the JavaScript section, as it will change the page URL and I guess you are trying to include this script into the pages. So, I will take the help of call_user_func() and the final "else" part after the setcookie() lines will be changed with the following line:
call_user_func("sesion");
Hope this will make sense now.

Categories