Skip to content

Instantly share code, notes, and snippets.

@vibby
Created December 20, 2016 16:38
Show Gist options
  • Save vibby/99a2dd715737a4db8ba4013cd86fc1b3 to your computer and use it in GitHub Desktop.
Save vibby/99a2dd715737a4db8ba4013cd86fc1b3 to your computer and use it in GitHub Desktop.
check session availability in PHP
<?php
session_start();
$sessPath = ini_get('session.save_path');
$sessCookie = ini_get('session.cookie_path');
$sessName = ini_get('session.name');
$sessVar = 'foo';
$essValue = 'hello world';
echo '<br>sessPath: ' . $sessPath;
echo '<br>sessCookie: ' . $sessCookie;
echo '<hr>';
$action = isset($_GET['action']) ? $_GET['action'] : 0;
if( $action == 1 ){
$_SESSION[$sessVar] = $essValue;
echo 'Session key ' . $sessVar . ' was set';
echo '<br>'.$sessVar . ': ' . $essValue;
}elseif( $action == 2 ){
// printing session value and global cookie PHPSESSID
echo $sessVar . ': ';
if( isset( $_SESSION[$sessVar] ) ){
echo $_SESSION[$sessVar];
}else{
echo '[not exists]';
}
echo '<br>' . $sessName . ': ';
if( isset( $_COOKIE[$sessName] ) ){
echo $_COOKIE[$sessName];
}else{
if( isset( $_REQUEST[$sessName] ) ){
echo $_REQUEST[$sessName];
}else{
if( isset( $_SERVER['HTTP_COOKIE'] ) ){
echo $_SERVER['HTTP_COOKIE'];
}else{
echo 'problem, check your PHP settings';
}
}
}
} elseif( $action == 3 ){
// destroy session by unset() function
echo 'Try to unset session key «'.$sessVar.'»';
unset( $_SESSION[$sessVar] );
// check if was destroyed
if( !isset( $_SESSION[$sessVar] ) ){
echo '<br>'.$sessName . ' was "unseted"';
}else{
echo '<br>'.$sessName . ' was not "unseted"';
}
}
?>
<hr>
<a href=<?php echo basename(__FILE__) ?>?action=1>Define value in session</a><br />
<a href=<?php echo basename(__FILE__) ?>?action=2>Printing value from session</a><br />
<a href=<?php echo basename(__FILE__) ?>?action=3>Remove value in session</a><br />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment