I am trying to create a login system. At the moment everything seem to be working as expected except I am not able to clear my session ID,
why do session_unset() and session_destroy don't seem to have any effect ?
UPDATE: solved below
INDEX.PHP
session_start();
if (array_key_exists('id', $_COOKIE) && $_COOKIE ['id']) {
$_SESSION['id'] = $_COOKIE['id'];
print("SESSION ID");
print("<br>");
print_r($_SESSION);
print("<br>");
print("COOKIE");
print("<br>");
print_r($_COOKIE);
}
// SET SESSION
function setSession($setSessionData) {
$_SESSION['id'] = $setSessionData[0];
if ($setSessionData[1] == 'yes') {
setcookie('id', $setSessionData[0], time() + 60*60*24*365, '/' );
}
};
// CLEAR SESSION
function unSetSession() {
session_unset();
setcookie("id", "", time() - 60*60*24*365, '/');
session_destroy();
}
SOLVED:
Had to initialise the session in my function called via Ajax; so the logout function is like so:
function unSetSession() {
session_start();
$_SESSION = array();
setcookie("id", "", time() - 60*60*24*365, '/');
session_destroy();
}
Related
I am trying to delete a cookie by setting that cookie in past time:
$cookie_name = "user";
$cookie_value = "david";
//subtraction from time causes deletion of cookie
setcookie($cookie_name, $cookie_value, time() - (86400 * 30), "/");
With the below code I try to check whether cookie is enabled or not and it returns if case rather than else part, while I already dell that cookie:
//counting number of cookies
if(count($_COOKIE) > 0) {
echo "<br>Cookies are enabled/exists";
} else {
echo "<br>Cookies are disabled/not exists";
}
But the else part is not working when we delete cookie and I don't know why?
The main problem is you just set user cookie time to past date not all the other cookie in super global $_COOKIE array . Try like this way to set for all $_COOKIE value using foreach() to past date and then check count condition.
<?php
$cookie_name = "user";
$cookie_value = "david";
$past_time = time() - 3600;
//use look set all cookie time to past date.
foreach ( $_COOKIE as $key => $value )
{
setcookie( $key, $value, $past_time, '/' );
}
//counting number of cookies
if(count($_COOKIE) > 0) {
echo "<br>Cookies are enabled/exists";
} else {
echo "<br>Cookies are disabled/not exists";
}
?>
DEMO: https://3v4l.org/jvRXW
I tried many ways to set a cookie, but when I get the cookie the value's not set. My code is placed before the <!DOCTYPE html>:
<?php
$url = explode('/', $_GET['url']);
$ref = $url[1];
$cookie_name = "refid";
$cookie_value = $ref;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/", "", 0);
?>
The $url[1] is set, I can see it in print_r() the problem is getting the cookie from a different page the calling code is:
<?php
if (!isset($_COOKIE['refid'])) {
echo "<br/>Cookie named refid is not set!";
} else {
echo "<br/>Cookie refid is set!<br>";
echo "Value is: " . $_COOKIE['refid'];
}
?>
Please help to resolve my problem.
Add this line:
$_COOKIE[$cookie_name] = $cookie_value;
after you set the cookie:
<?php
$url=$_GET['url'];
$url=explode ('/',$_GET['url']);
$ref=$url[1];
$cookie_name = "refid";
$cookie_value = $ref;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/", "", 0);
$_COOKIE[$cookie_name] = $cookie_value;
?>
The setcookie() does not update the current $_COOKIE variable, which will be instantiated when the script loads. The variable will first be updated next time you load the script.
I'm still new in PHP language and trying out on how to set Session Timeout, which ensure that when user log in to their account, it will limit to few minutes / 1 hour before the account got logout automatically when user log in too long. I refered to this link.
http://bytes.com/topic/php/insights/889606-setting-timeout-php-sessions
index.php
<?php
if(!isset($_SESSION))
{
session_start();
}
$timeout = $_SERVER['REQUEST_TIME'];
/**
* for a 1 minute timeout, specified in seconds
*/
$timeout_duration = 60;
if (isset($_SESSION['LAST_ACTIVITY']) && ($timeout - $_SESSION['LAST_ACTIVITY']) > $timeout_duration) {
session_unset();
session_destroy();
session_start();
}
$_SESSION['LAST_ACTIVITY'] = $timeout;
?>
coupon.php
<?php
// error_reporting(E_ALL); ini_set("display_errors", 1);
session_start();
$timeout = 60; // Number of seconds until it times out.
// Check if the timeout field exists.
if(isset($_SESSION['timeout'])) {
$duration = time() - (int)$_SESSION['timeout'];
if($duration > $timeout) {
// Destroy the session and restart it.
session_destroy();
}
}
// Update the timeout field with the current time.
$_SESSION['timeout'] = time();
// include ('sessionTimeout.php');
if( !isset($_SESSION["loginSuccess"]) ){
echo "<script type='text/javascript'>alert('Login failed!');</script>";
die('<meta http-equiv="refresh" content="0;URL=\'login-redirect.php\'" />');
}
?>
sessionTimeout.php
<?php
function session_start_timeout($timeout=5, $probability=100, $cookie_domain='/') {
// Set the max lifetime
ini_set("session.gc_maxlifetime", $timeout);
// Set the session cookie to timout
ini_set("session.cookie_lifetime", $timeout);
$seperator = strstr(strtoupper(substr(PHP_OS, 0, 3)), "WIN") ? "\\" : "/";
$path = ini_get("session.save_path") . $seperator . "session_" . $timeout . "sec";
if(!file_exists($path)) {
if(!mkdir($path, 600)) {
trigger_error("Failed to create session save path directory '$path'. Check permissions.", E_USER_ERROR);
}
}
ini_set("session.save_path", $path);
// Set the chance to trigger the garbage collection.
ini_set("session.gc_probability", $probability);
ini_set("session.gc_divisor", 100); // Should always be 100
// Start the session!
session_start_timeout(60, 10);
if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), $_COOKIE[session_name()], time() + $timeout, $cookie_domain);
}
}
?>
logout.php
<?php
session_start();
include('config.php');
foreach($_SESSION as $key => $value){
if (strpos($key, $PROJECT_NAME) !== FALSE){
unset($_SESSION[$key]);
}
}
$_SESSION[$PROJECT_NAME . 'logout'] = true;
session_destroy();
//print_r($_SESSION);
header('Location:' . $base_url . 'index');
?>
Am i missing out something? This is because my session timeout doesn't work.
Start a Javascript timer when the page loads and redirect the user to the logout page when the timer expires.
<script type="text/javascript">
setTimeout(function() { window.location.href = "logout.php"; }, 60 * 60 * 1000);
</script>
This question already has answers here:
Why Session object destruction failed
(4 answers)
Closed 8 years ago.
i ve seen so many questions about this and im still having problems with that... can someone give me a help?
login page :
<?PHP
header("Content-Type: text/html; charset=utf-8");
$login = "root";
$senha = "test";
session_start();
session_set_cookie_params(0);
if ($_POST['login'] && $_POST['senha']) {
if ($login == $_POST['login'] && $senha == $_POST['senha']) {
$_SESSION['login'] = $login;
$_SESSION['senha'] = $senha;
Header("Location: index.php");
} else {
unset ($_SESSION['login']);
unset ($_SESSION['senha']);
header("Location: login.php");
}
}
?>
logout page :
<?php
session_start();
$_SESSION = array();
unset( $_SESSION['login'] );
unset( $_SESSION['senha'] );
setcookie(session_name(), '', time() - 3600, '/');
session_destroy();
Header("Location: login.php");
exit();
?>
im getting this error:
PHP Warning: session_destroy(): Session object destruction failed in \\N\Users\cPanel\gil\public_html\gilberto\logout.php on line 11
This is my usual approach, see the comments for further details.
session_start();
// 1. unset all of the session variables
$_SESSION = array();
// 2. delete the session cookie
if ( ini_get( 'session.use_cookies' ) ) {
$params = session_get_cookie_params();
setcookie( session_name(), '', ( time() - 42000 ), $params['path'], $params['domain'], $params['secure'], $params['httponly'] );
}
// 3. destroy the session.
session_destroy();
You don't have to make $_SESSION = array();
Just use session_destroy() like said here :
http://www.php.net/manual/fr/function.session-destroy.php
Here is a function i use to logout:
function logout(){
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode('=', $cookie);
$name = trim($parts[0]);
if(strtoupper($name) == 'PHPSESSID'){
continue;
}
setcookie($name, '', time()-360000);
setcookie($name, '', time()-360000, '/');
}
foreach($_SESSION as $key => $val){
unset($_SESSION[$key]);
}
header('Location: account/login');
die;
}
i have this code im trying to do for a type of cache system so it remembers the city the user has selected. if the user has selected a city it stores it in sessions and cookies, and will automatically redirect them to the city page if they've selected it before.
sessions work fine, but it doesn't seem to be setting the cookie to an empty value if the $_GET['city'] variable is empty...
heres my code:
function gen_url ($city)
{
$url = 'http://www.mysite.com';
if (!empty($city)) $url .= "/c-$city";
return $url;
}
function set_cache ($variable, $value)
{
$_SESSION[$variable] = $value;
setcookie($variable, $value, time() + 31536000);
}
$redirect = false;
$redirect_array['city'] = '';
if (!empty($_GET['city']))
{
$sql = mysql_query("select * from `cities` where `slug`='".mysql_real_escape_string($_GET['city'])."'");
if (mysql_num_rows($sql) != 0)
{
while ($row = mysql_fetch_assoc($sql))
{
foreach ($row as $k => $v)
$city[$k] = $v;
}
$redirect_array['city'] = $city['slug'];
}
else
{
$redirect = true;
}
}
if ($redirect)
{
header('Location: '.gen_url($redirect_array['city']);
die();
}
set_cache('city', $redirect_array['city']);
You can't set a cookie with an empty string as it will delete the cookie.
From the docs:
If the value argument is an empty string, or FALSE, and all other
arguments match a previous call to setcookie, then the cookie with the
specified name will be deleted from the remote client.
You can't set a cookie to most falsy values to indicate falseness of a trit cookie. Only '0' will work. Use that.
PHP's setcookie() doesn't allow you to set cookies with empty values. But you can do that with header()
replace:
setcookie($variable, $value, time() + 31536000);
with:
header('set-cookie: '.rawurlencode($variable).'='.rawurlencode($value).'; max-age=31536000', false);
You can set empty value to the cookie by using null pointer as the value
like this:
setrawcookie('testEmptyCookie', "\x00", time() + 3600, '/');
(tried on php 5.6, 7.2)
Make sure to set your cookie with a negative time:
setcookie($variable, '', -1);