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)
Related
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 ();
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
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);
I'm not sure if somebody asked this already, at least i cant find the answer so i'm wondering what i'm doing wrong with my script.
I'm trying to delete a cookie with a callback done by Jquery that calls a php script on the background, BUT, whatever i try i cannot get this to properly work (deleting the cookie).
I've checked the php website and even looked at the RFC 2109 memo to find out how browsers and php try to accomplish that the cookie will be deleted.
So, my question here is; How can this fail?
Edit: i don't get any error message, deleting the cookie manually works and creating the cookie with the same type of callback done by jquery does also work. It just doesn't get deleted when i try the same callback with jquery to run the PHP script in the background in order to delete the cookie.
Code for that JQ callback action:
$(document).ready(function() {
var alert = $('#Cmessage');
$(".delete").on('click', function(){
$.ajax({
url: 'http://www.oostpijl.nl/shop/offerte/deletecookie.php',
type: 'get', // form submit method get/post
dataType: 'json', // request type html/json/xml
beforeSend: function() {
alert.fadeOut();
},
success: function(result) {
if(result.error){
alert.html(result.html).fadeIn();
console.log(e)
}else{
alert.html(result.html).fadeIn();
}
}
});
});
});
PHP script:
<?php
include("_offertesettings.php");
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
setcookie('offerte', '', time() - 3600, '/' , '.oostpijl.nl' );
setcookie('offerteC', '', time() - 3600, '/', '.oostpijl.nl' );
$result = array("error" => false, "html" => null);
$result["error"] = false;
$result["html"] = "<script type='text/javascript'>setTimeout(function() { window.location='" . $config["BURL"] . "'; }, 10);</script>";
} else {
$result["error"] = true;
$result["html"] = "<h3>Error; Neem contact op met de webmaster</h3>";
}
echo json_encode($result);
exit;
?>
Make sure you get inside your isset condition. You should test it by printing something as a test then exit.
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
echo json_encode('test');
exit;
}
also make sure there is no error in your included file "_offertesettings.php". You can check if there are PHP errors by adding those lines at the top of your PHP script.
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
to delete your cookies you just need this:
setcookie('offerte', '', time() - 3600);
setcookie('offerteC', '', time() - 3600);
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)