Problems with deleting $_SESSION in PHP - php

I'm having a problem with deleting the session. It's stored in the cookies, and whenever I click on the log out button, nothing happens.
HTML
<input id="log_out_button" onclick="logout()" type="button" value="Log Out">
AJAX
function logout() {
// Create request object
var request = new XMLHttpRequest();
// Create event handler that specifies what should happen when server responds
request.onload = function() {
// Check HTTP status code
if(request.status == 200) {
document.getElementById("error_messages").innerHTML = "";
}
else
alert("Error communicating with server: " + request.status);
}
// Set up request with HTTP method and URL
request.open("GET", "php/log_out.php");
//Send request
request.send();
}
PHP
<?php
//Start session management
session_start();
//Remove all session variables
session_unset();
//Destroy the session
session_destroy();
?>

session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
so if you want to close user session, you also need to clear cookies
setcookie(session_name(), false, -1, '/');
http://php.net/manual/en/function.setcookie.php
http://php.net/manual/en/function.session-start.php

Related

Json Syntax Error on Session Expire

I'm working with Slim Framework and I would like to redirect the user to the login page if the user has lost his session but I'm always getting a SyntaxError : Unexpected token < at position 0.
My session validation code in php is this:
private function _validaSessao() {
$user = $this->userData['IdUser'];
if(null === $user || trim($user) == '') {
header("Location: http://192.168.0.9/", true, 301);
die();
}
}
I've tried that and all the following:
header('refresh:5;url=http://192.168.0.9/');
echo '<script>window.location.href = "http://192.168.0.9/";</script>';
return('<script>window.location.href = "http://192.168.0.9/";</script>');
echo json_encode('<meta HTTP-EQUIV="REFRESH" content="0; url=http://192.168.0.9/">');
I've tried them all and I'm always getting
200 ---- SyntaxError: Unexpected token < in JSON at position 0
The only piece of code that worked for me was:
echo json_encode(array(
'SemSessao' => true
));
But the above code makes me checking on every single call on JavaScript and I would like a solution that PHP will redirect me. This way I wouldn't need to keep checking on every single JS call (which are a lot) and each time a php object was instanciated it would check for session and redirect the user without the use of JS.
Update 1 - Include JS code (lovely downvotes everywhere :D)
getDadosPlaneamento: function() {
var req = {Rota: '/planeamento/getDados/AUTO'};
var dfd = $.Deferred();
$.when(App.gajax(req)).done(function(d) {
On.Planeamentos = d.Planeamentos;
dfd.resolve();
});
return dfd.promise();
},
The above code is what refers to my php route and then:
$onapp->get('/planeamento/getDados/:tipo/', function($tipo) {
if ($tipo == 'AUTO') {
$P = new MongoApi\Planeamento();
$ret = array(
$P->getAllMongo();
);
}
echo json_encode($ret);
});
And when I do $P = new MongoApi\Planeamento(); I check if the user has a valid session on the constructor using _validaSessao();
The server cannot redirect a client from an AJAX call. The AJAX call is a background HTTP request. Whether that HTTP requests gets redirected or not is irrelevant to the browser. The browser will return the request response to the AJAX client, and if that response is "your request has been redirected" then that's that. Again, a redirect doesn't redirect "the browser", it redirects the HTTP request. Or more precisely speaking, it tells the HTTP client that it should retry its request somewhere else; nothing more.
If your AJAX requests can fail due to a session timeout and whenever that happens you want to present the user with a login page, you will have to do that client side. In order to not repeat that same code every time, you make a function/object/service out of that. E.g. something along the lines of:
function makeAJAXRequest(url, data) {
return fetch(url)
.then(response => {
if (response.status == 403) {
window.location = '/login';
throw new Error('Forbidden');
} else {
return response;
}
});
}
Here the server is expected to respond with a 403 Forbidden status code for unauthorised requests. If you make all your AJAX requests through this function, it will automatically handle that case by redirecting to the login page.
Remeber that header() must be called before any output is generated. you can use ob_start() and op_end_flush() to avoid output previous to your header.
ob_start ();
header ("Location: http://192.168.0.9/", true, 301);
ob_end_flush ();

Checking For Cookie Right After Setting Cookie [duplicate]

I'm trying to access a cookie's value (using $_COOKIE) immediately after calling the setcookie() function in PHP. When I do so, $_COOKIE['uname'] isn't set. Why?
Note, however, that $_COOKIE['uname'] is set as expected upon the next execution of the script, such as after a page refresh.
setcookie('uname', $uname, time() + 60 * 30);
echo "Cookie value: " . $_COOKIE['uname'];
The cookie isn't set until the response is sent back to the client, and isn't available in your PHP until the next request from the client after that.
However, when you set the cookie in your script, you can do:
setcookie('uname', $uname, time()+60*30);
$_COOKIE['uname'] = $uname;
$_COOKIE is set when the page loads, due to the stateless nature of the web. If you want immediate access, you can set $_COOKIE['uname'] yourself or use an intermediate variable.
For example:
if (isset($_COOKIE['uname'])) {
// get data from cookie for local use
$uname = $_COOKIE['uname'];
}
else {
// set cookie, local $uname already set
setcookie('uname', $uname, time() + 1800);
}
If you want to access a cookie's value immediately after calling the setcookie() you can't use $_COOKIE. The reason for this is in the nature of the protocol (see https://www.rfc-editor.org/rfc/rfc6265). When you use setcookie() it defines a Cookie to be sent along with the rest of the HTTP headers to the client (see http://php.net/manual/en/function.setcookie.php). But $_COOKIE on the other hand contains variables passed to the current script via HTTP Cookies from the client (http://php.net/manual/en/reserved.variables.cookies.php).
When you change $_COOKIE after calling setcookie() - like some answers here recommend - it doesn't contain only the Cookies from the client any more. This could interferer with assumptions made in third party code used in your application and may result in unwanted site effects. So in general it's not good practice and it's only an option when the calls of setcookie() are part of your own code.
A clean and transparent way to get a value set with setcookie() within the same request is to use headers_list() (see http://php.net/manual/en/function.headers-list.php):
function getcookie($name) {
$cookies = [];
$headers = headers_list();
// see http://tools.ietf.org/html/rfc6265#section-4.1.1
foreach($headers as $header) {
if (strpos($header, 'Set-Cookie: ') === 0) {
$value = str_replace('&', urlencode('&'), substr($header, 12));
parse_str(current(explode(';', $value, 1)), $pair);
$cookies = array_merge_recursive($cookies, $pair);
}
}
return $cookies[$name];
}
// [...]
setcookie('uname', $uname, time() + 60 * 30);
echo "Cookie value: " . getcookie('uname');
But notice this won't work in PHP CLI (e.g. PHPUnit). In such a case you could use third party extensions like XDebug (see http://xdebug.org/docs/all_functions#xdebug_get_headers).
You have to set the cookie variable by yourself if you need it immediately, by the time you load another page the real cookie would have been set as a result of the setcookie method.
setcookie('name', $value, time()+60*30);
$_COOKIE ['name'] = $value;
We can do this using AJAX calling.
If we want to create cookies on button click so first create a AJAX call for creating cookies then the success of first AJAX calling we can call another AJAX for getting the cookies.
function saveCookie() {
var base_url = $('#base_url').val();
var url = base_url + '/index/cookie';
$.ajax({
'url': url,
'type': 'POST',
'success': function (data) {
if (data) {
var url = base_url + '/index/get_cookie';
$.ajax({
'url': url,
'type': 'POST',
'success': function (response) {
var container = $('#show');
if (response) {
container.html(response);
}
}
});
}
}
});
}
<button type="button" onclick="saveCookie()">Save Cookie</button>
<div id="show"></div>
I had a similar problem where i used a function from a included file and solved it with a function that both returns the value of the cookie and sets the cookie.
function setCookie($input) {
setcookie('uname', $input, time() + 60 * 30);
return $input;
}
if(!isset($_COOKIE['uname'])) {
$uname = setCookie($whatever);
} else {
$uname = $_COOKIE['uname'];
}
echo "Cookie value: " . $uname;
Using ob_start() and ob_flush() you can send the cookie to client and retrieve it in the same run time. Try this:
ob_start();
setcookie('uname', $uname, time() + 60 * 30);
ob_flush();
echo "Cookie value: " . $_COOKIE['uname'];
Your script's setcookie() function runs when the web browser requests the page for the first time, in your case the reload. This cookie is stored in the users browser and isn't available to your script running on the server until the next request, or in your case the next reload.
Upon the next request the browser sends that cookie to the server and the array $_COOKIE will have the value that you initially set and the browser sent back upon the second request.
I set a constant at the same time the cookie was created
define('CONSTANT', true);
return setcookie('cookiename', 'cookie value goes here', time() + 60 * 60 * 24 * 30, '/');
I can then immediately do something by:
if(isset($_COOKIE['cookiename']) || $_COOKIE['cookiename'] || defined('CONSTANT') && CONSTANT)

cookie is not working

I set cookie in php by sending values through post but on redirect cookie, it showing that cookie is not set.
//username is just stored here for an example, it is not a good process to store credentials in cookie.
$('.loginDialogBtn').click(function() {
$usernameLogIn = $('#usernameLogIn').val();
var $passwordLogIn = $('#passwordLogIn').val();
$.post('authorizationAdmin.php', {
usernameLogIn: $usernameLogIn,
passwordLogIn: $passwordLogIn
}, function(data) {
var response = JSON.parse(data);
if (response['done'] === $usernameLogIn ) {
location.href = 'http://foodinger.in/Admin/home.php?restUsername=' + $usernameLogIn;
}
else {
$('.loginError').html('Incorrect Username and password');
}
});
});
php
if(isset($_POST['usernameLogIn']) && !empty($_POST['usernameLogIn']) && isset($_POST['passwordLogIn']) && !empty($_POST['passwordLogIn'])) {
$Username=strip_tags(trim($_POST['usernameLogIn']));
$password = strip_tags(trim($_POST['passwordLogIn']));
setcookie('username',$username, time() + (83600*30), "/Admin/", '.foodinger.in');
setcookie('restaurantId',$restId, time() + (83600*30), "/Admin/", '.foodinger.in');
}
after click on login button i can see cookie is being set in my browser but i can't fetch it using $_COOKIE.
is there any server setting which could make it wrong ?
update -- i was using "walkme" which created the problem, once i removed walkme and deleted all the cookies, it worked. Can anyone please
tell me why "walkme" is creating problem in fetching my cookie
variables
Thanks in advance
Try this to debug your cookie :
// Print an individual cookie
echo $_COOKIE["username"];
echo $HTTP_COOKIE_VARS["username"];
// Another way to debug/test is to view all cookies
print_r($_COOKIE);

Passing a $_SESSION failed when creating the $_SESSION within Ajax function

I have a simple registration form and the new comers will be registered with an ajax function. There I create a $_SESSION['is_logged'] when the registration is finished.
On var_dumb I get that the var is set. But when redirect on another page it is empty (I have included already the session_start() on the both pages...
I have read somewhere in the net that:
"Sessions are ONLY written on a page load/refresh".
Is this the case, or I have to look for some other issues within my code.
the ajax:
$.ajax({
url:"../controllers/register.php",
type:"POST",
data:res,
success: function(responce){
if (responce==1) {
$('#msg').addClass('msg-warning');
$("#form").css('display',"none");
$('#msg').append("<p>It seems that you have already submited the form. Click to "+
" <a href='login.php'>log-in</a> or to <a href='register.php'>register</a>.</p>");
}
else if (responce==2) {
$('#msg').addClass('msg-warning');
$("#form").css('display',"none");
$('#msg').append("<p>You have successfully created account. Click to "+
" <a href='start.php'>welcome</a> to start your .</p>");
$('.menu').append("<li><a href='logout.php'>Log out</a></li>")
}
else{
$('#msg').text(responce);
}
},
error: function(){
$('#msg').text("Opss, try again");
}
});
the register.php file:
if (isset($_SESSION['submited'])) {
echo 1;
exit;
}
include_once('../models/functions.php');
// Give the post parametters to another var
$arr=$_POST;
// function for uploading
$reg = registerMe($arr);
if ($reg === true) {
$_SESSION['submited']=1;
$_SESSION['is_logged']=1
echo(2);
}
else{
echo($reg);
}
exit;
The session_start(); is included in the header of the first page where from the ajax is started.And the second page - where the $_SESSION['is_logged'] is lost, again the session_start(); is part of dc_header(); function. start.php:
<?php
dc_header("Речник|Регистрация");
if (!isset($_SESSION['is_logged'])) {
#header("location: ../views/login.php");
var_dump($_SESSION);
}
?>
add
session_start();
to the top of register.php
You need to specify session_start, so your server who was commanded to execute "register.php" (either from ajax, direct call, browser scripts, cron job or whatever possible you-name-it) will handle the execution and the setting of $_SESSION variables in reference to the connected clients session. Server won't guess by itself that this is an "ajax call from an already session_start page". You need to specify that whatever is done in register.php is done in the current client's session.

Accessing $_COOKIE immediately after setcookie()

I'm trying to access a cookie's value (using $_COOKIE) immediately after calling the setcookie() function in PHP. When I do so, $_COOKIE['uname'] isn't set. Why?
Note, however, that $_COOKIE['uname'] is set as expected upon the next execution of the script, such as after a page refresh.
setcookie('uname', $uname, time() + 60 * 30);
echo "Cookie value: " . $_COOKIE['uname'];
The cookie isn't set until the response is sent back to the client, and isn't available in your PHP until the next request from the client after that.
However, when you set the cookie in your script, you can do:
setcookie('uname', $uname, time()+60*30);
$_COOKIE['uname'] = $uname;
$_COOKIE is set when the page loads, due to the stateless nature of the web. If you want immediate access, you can set $_COOKIE['uname'] yourself or use an intermediate variable.
For example:
if (isset($_COOKIE['uname'])) {
// get data from cookie for local use
$uname = $_COOKIE['uname'];
}
else {
// set cookie, local $uname already set
setcookie('uname', $uname, time() + 1800);
}
If you want to access a cookie's value immediately after calling the setcookie() you can't use $_COOKIE. The reason for this is in the nature of the protocol (see https://www.rfc-editor.org/rfc/rfc6265). When you use setcookie() it defines a Cookie to be sent along with the rest of the HTTP headers to the client (see http://php.net/manual/en/function.setcookie.php). But $_COOKIE on the other hand contains variables passed to the current script via HTTP Cookies from the client (http://php.net/manual/en/reserved.variables.cookies.php).
When you change $_COOKIE after calling setcookie() - like some answers here recommend - it doesn't contain only the Cookies from the client any more. This could interferer with assumptions made in third party code used in your application and may result in unwanted site effects. So in general it's not good practice and it's only an option when the calls of setcookie() are part of your own code.
A clean and transparent way to get a value set with setcookie() within the same request is to use headers_list() (see http://php.net/manual/en/function.headers-list.php):
function getcookie($name) {
$cookies = [];
$headers = headers_list();
// see http://tools.ietf.org/html/rfc6265#section-4.1.1
foreach($headers as $header) {
if (strpos($header, 'Set-Cookie: ') === 0) {
$value = str_replace('&', urlencode('&'), substr($header, 12));
parse_str(current(explode(';', $value, 1)), $pair);
$cookies = array_merge_recursive($cookies, $pair);
}
}
return $cookies[$name];
}
// [...]
setcookie('uname', $uname, time() + 60 * 30);
echo "Cookie value: " . getcookie('uname');
But notice this won't work in PHP CLI (e.g. PHPUnit). In such a case you could use third party extensions like XDebug (see http://xdebug.org/docs/all_functions#xdebug_get_headers).
You have to set the cookie variable by yourself if you need it immediately, by the time you load another page the real cookie would have been set as a result of the setcookie method.
setcookie('name', $value, time()+60*30);
$_COOKIE ['name'] = $value;
We can do this using AJAX calling.
If we want to create cookies on button click so first create a AJAX call for creating cookies then the success of first AJAX calling we can call another AJAX for getting the cookies.
function saveCookie() {
var base_url = $('#base_url').val();
var url = base_url + '/index/cookie';
$.ajax({
'url': url,
'type': 'POST',
'success': function (data) {
if (data) {
var url = base_url + '/index/get_cookie';
$.ajax({
'url': url,
'type': 'POST',
'success': function (response) {
var container = $('#show');
if (response) {
container.html(response);
}
}
});
}
}
});
}
<button type="button" onclick="saveCookie()">Save Cookie</button>
<div id="show"></div>
I had a similar problem where i used a function from a included file and solved it with a function that both returns the value of the cookie and sets the cookie.
function setCookie($input) {
setcookie('uname', $input, time() + 60 * 30);
return $input;
}
if(!isset($_COOKIE['uname'])) {
$uname = setCookie($whatever);
} else {
$uname = $_COOKIE['uname'];
}
echo "Cookie value: " . $uname;
Using ob_start() and ob_flush() you can send the cookie to client and retrieve it in the same run time. Try this:
ob_start();
setcookie('uname', $uname, time() + 60 * 30);
ob_flush();
echo "Cookie value: " . $_COOKIE['uname'];
Your script's setcookie() function runs when the web browser requests the page for the first time, in your case the reload. This cookie is stored in the users browser and isn't available to your script running on the server until the next request, or in your case the next reload.
Upon the next request the browser sends that cookie to the server and the array $_COOKIE will have the value that you initially set and the browser sent back upon the second request.
I set a constant at the same time the cookie was created
define('CONSTANT', true);
return setcookie('cookiename', 'cookie value goes here', time() + 60 * 60 * 24 * 30, '/');
I can then immediately do something by:
if(isset($_COOKIE['cookiename']) || $_COOKIE['cookiename'] || defined('CONSTANT') && CONSTANT)

Categories