PHP cookie value not being passed from one page to another - php

This is in a page called headersessioncookie.php
<?php
session_start();
if ( ! isset ( $_SESSION['loggedin'] ) ) {
$_SESSION['loggedin'] = FALSE;
}
$expiry = time()+60*60*9000;
setcookie('cookie[loggedin]', '', $expiry, "", "", "", TRUE);
if ( ! isset ( $_COOKIE['cookie[loggedin]'] ) ) {
$_COOKIE['cookie[loggedin]'] = FALSE;
}
?>
This is in a page called test.php
<?php
require_once('headersessioncookie.php'); //start session and cookie
$_SESSION['loggedin'] = TRUE;
$_COOKIE['cookie[loggedin]'] = TRUE;
?>
When I run test.php and then run this page below called test1.php ...
<?php
require_once('headersessioncookie.php'); //start session and cookie
echo "sessionvalue" . $_SESSION['loggedin'] . '<br>';
echo "cookievalue" . $_COOKIE['cookie[loggedin]'] . '<br>';
?>
... I get
sessionvalue1
cookievalue
Why don't I get...
sessionvalue1
cookievalue1
...??

The superglobal variable $_COOKIE only contains the cookie values. If you modify this value won't affect to the cookie because you need to sent the headers to the browser to do so.
If you need to modify it you have to use the method setCookie because this will sent the headers with the new value.
Note Remember that the $_COOKIE only will be updated after use setCookie when you refresh the page.

So this should work:
File: headersessioncookie.php
<?php
//Session
session_start();
if ( !isset($_SESSION['loggedin']) )
$_SESSION['loggedin'] = FALSE;
//Cookie
$expiry = time()+60*60*9000;
if ( !isset($_COOKIE['cookieloggedin']) )
setcookie('cookieloggedin', '', $expiry, "", "", true);
?>
File: test.php
<?php
require_once('headersessioncookie.php'); //start session and cookie
$_SESSION['loggedin'] = TRUE;
setcookie('cookieloggedin', '1', $expiry, "", "", true);
?>
File: test1.php
<?php
require_once('headersessioncookie.php'); //start session and cookie
echo "sessionvalue" . $_SESSION['loggedin'] . '<br>';
echo "cookievalue" . $_COOKIE['cookieloggedin'] . '<br>';
?>
Please notice also:
-How to update a cookie: https://stackoverflow.com/a/6487597/3933332
-Is a Cookie Case Sensitive: https://stackoverflow.com/a/11312272/3933332

Answering my own question. Turns out there were 3 major problems with my code.
1) I was trying to set the cookie value by doing this:
$_COOKIE['cookie[loggedin]'] = FALSE;
Turns out one needs to use setcookie() to set the cookie value. Assigning a new value to $_COOKIE will change the value of that variable (within the scope of the same page), but it won't change the value inside the cookie (outside the scope of that page, calling $_COOKIE will yield the value stored in the cookie).
2) The following is incorrect
echo "cookievalue" . $_COOKIE['cookie[loggedin]'] . '<br>';
Instead it should be
echo "cookievalue" . $_COOKIE['cookie']['loggedin'] . '<br>';
3) Cookie necessarily has to be passed a string value. I was trying to pass a value = FALSE which is not a string. Instead, I could have correctly passed a value = 'FALSE'

Related

How to match $_SESSION with if..else?

Here i have an if else that create cookie with name check_CookiesRW and with content randomly generated by rand(1000,999999);. I would love to check if the cookie content randomly generated and stored on $_SESSION would match and echo out Cookie is SET something like this
if(isset($_COOKIE['check_CookiesRW']) && $_COOKIE['check_CookiesRW'] === $_SESSION['cookie_content'])
how can i achieve this without it throwing out error Warning: Undefined variable $_SESSION ??
<?php
if(isset($_COOKIE['check_CookiesRW'])) {
print "<h1>Cookie is SET</h1>";
} else {
$cookie_name = "check_CookiesRW";
$cookie_content = rand(1000,999999);
$_SESSION['cookie_content'] = $cookie_content;
setcookie($cookie_name, $cookie_content, time()+30, "/");
print "<h1>Created Cookie</h1>";
}
?>

PHP opens 2nd session unwanted

Requirement: use QRBOT-app to scan a barcode on a mobile and give the number scanned to the website.
Problem: I've a session open (1), from here I'm opening the app (see ScanBardcode.php), I scan and the app returns to the callback-URL including the required parameters. However I do expect it is re-using it's session, it creates a new one (2). Can someone help me? It does have both sessions active and both pages keep using it's own session. I can only test it on my cell phone, which I checked is using each time (the initiate-1 and the callback-2 the same browser)
What I tried already:
1. Pass the sessionID in the callback URL (QRBOT doesn't allow parameters)
2. Set Session.auto_start to 1
ScanBarcode.php
<?php
include_once('../../config.inc.php'); //contains DB connection details and other settings
include_once($fullurl . '../../admin/includes/sessie.inc.php'); //generates session
echo "SessionID=". session_id() . "!";
$_SESSION['BarCode'] = "VoorraadTellen";
echo "Wat gaan we doen? " . $_SESSION['BarCode'] . "</br></br>";
//URL to open qrbot.
echo "click"
?>
ScanBarcodeCallBack.php
<?php
$source = $_GET['x-source'];
$content = $_GET['content'];
$format = $_GET['format'];
include_once('../../config.inc.php');
include_once($fullurl . '../../admin/includes/sessie.inc.php');
echo "Wat gaan we doen? " . $_SESSION['BarCode'] . "</br></br>";
echo "SessionID=". session_id() . "!";
echo $source . $content . $format;
// HERE I WRITE TO THE DB.
?>
sessie.inc.php
<?php
$a = session_id();
if(empty($a))
{
session_start();
}
if(isset($_SESSION['sgebruiker']))
{
$now = time();
if($now - $_SESSION['stijd'] > $_SESSION['maxidle'])
{
$_SESSION = array();
session_destroy();
}
else
{
$_SESSION['stijd'] = $now;
}
}
elseif(isset($_COOKIE['login_cookie']))
{
//Check against db and set cookie.
}
?>
Adding screenshot when I add the sessionId in the URL as a parameter:
enter image description here
Update to ScanBarcode.php
`echo "click"
as far as i know you don't need the whole check with session_id(). PHP Documentation for session_start() says:
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.
this is also my experience. every time i used session_start() i just put it at the top of every file (or included it like you did)
When you pass the session ID in the URL, you need to use the parameter to set the session ID before calling session_start(). Change sessie.inc.php to:
<?php
if (isset($_GET['s'])) {
session_id($_GET['s']);
}
session_start();
if(isset($_SESSION['sgebruiker']))
{
$now = time();
if($now - $_SESSION['stijd'] > $_SESSION['maxidle'])
{
$_SESSION = array();
session_destroy();
}
else
{
$_SESSION['stijd'] = $now;
}
}
elseif(isset($_COOKIE['login_cookie']))
{
//Check against db and set cookie.
}
?>
Working with both #Tsai and #Barmar we found the solution.
We fixed it by:
- Encoding the URL by using urlencode-function
- Take the sessionID from URL and apply that using session_id-function before initiating the start_session (see also).
The cleaned up code below; hopefully someone would be able to use it also.
ScanBarcode.php
<?php
include_once('../../config.inc.php'); //contains DB connection details and other settings
include_once($fullurl . '../../admin/includes/sessie.inc.php'); //generates session
echo "SessionID=". session_id();
//URL to open qrbot.
$CallbackUrl = "http://ilonashairstyling.nl/2016UAT/module/Ilonas_admin/ScanBarcodeCallBack.php?s=" . htmlspecialchars(session_id());
echo "click"
?>
ScanBarcodeCallBack.php
<?php
$source = $_GET['x-source'];
$content = $_GET['content'];
$format = $_GET['format'];
include_once('../../config.inc.php');
ini_set("session.use_cookies",0);
ini_set("session.use_trans_sid",1);
session_id($_GET['s']);
//print_r($_SESSION); //You can test it with this code
//print(session_id()); //You can test it with this code
ini_set("session.use_cookies",1);
ini_set("session.use_trans_sid",0);
include_once($fullurl . '../../admin/includes/sessie.inc.php');
echo "Wat gaan we doen? " . $_SESSION['BarCode'] . "</br></br>";
echo "SessionID=". session_id() . "!";
echo $source . $content . $format;
// HERE I WRITE TO THE DB.
?>
sessie.inc.php is unchanged

How To Get Cookie's Name In PHP?

I want to get cookie's name in PHP. Not cookie's value! My code like below:
<?php
session_start();
ob_start();
$user_id = $_GET["user_id"];
$timing_clock = "";
if(isset($_COOKIE["timing_type"])){
// cookie's value
$timing_clock = setcookie("timing_type");
// how to get cookie's name?
} else {
echo("0");
}
?>
How can i do that? I want to set cookie's name to a variable. Because cookie's name are very important for me.
it will help you, use var_dump($_COOKIE) and get all COOKIE name.
$cookie_name = "user";
$cookie_value = "Dave";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
if(isset($_COOKIE)) {
var_dump($_COOKIE);
foreach($_COOKIE as $key => $val)
{
echo "cookie name = ".$key.", and value = ".$val;
}
}
This will print all with respective name
<pre>
<?php print_r($_COOKIE); ?>
</pre>
In this example
setcookie("timing_type");
the cookie name would be $_COOKIE['timing_type']
When you use the setcookie function you are applying the cookie name(key).
All cookies names are stored in $_COOKIE as "Name" => "value".
Simply output the keys of the $_COOKIE array and you'll have your names :)
Simply read $_COOKIE["name"] to get the name set by setcookie
The first paramater of setcookie() is the name of the cookie
<?php
session_start();
ob_start();
$user_id = $_GET["user_id"];
$timing_clock = "";
if(isset($_COOKIE["timing_type"])){
// cookie's value
$timing_clock = setcookie("timing_type");
// how to get cookie's name?
$cookie_name = $_COOKIE['timing_type'];
} else {
echo("0");
}
?>
$_COOKIE["name"] = "JASON STATHAM";

PHP: Passing variable with cookie

What's the correct way of passing variable using PHP cookie. I can't seem to get it to work? I keep getting "FAILED!"
Here's my code:
On 1st page:
$crpid['ONE']="PAGE1";
$crpid['TWO']="PAGE2";
$crpid['THREE']="PAGE3";
$crp_id = $_SERVER["REDIRECT_URIPART"];
$crp_value = $crpid[$crp_id];
session_start();
setcookie('crpid', $crp_value, time()+3600, "/");
On 2nd page:
if(!isset($_COOKIE['crpid']) && $_COOKIE['crpid']==''){
echo "FAILED!";
}
else{
echo "Cookie ".$_COOKIE['crpid']." is set!";
}

php session variable doesnt carry over to redirect

Problem: Session variable doesnt carry over after the redirect.
facebook.php (session variable created, and stored)
button directs to available.php --> searching.php
I'm using header redirect. So $_SESSION['seshfbId'] echos on available.php but not searching.php
Code
facebook.php
<?php
session_start(); // start up your PHP session!
header( 'Location: http://www.redacted.co/chat.php' ) ;
function createSeshVariables($name, $email, $college, $photo, $id)
{
// set the value of the session variable 'name'
$_SESSION['seshName'] = $name;
// set the value of the session variable 'email'
$_SESSION['seshEmail'] = $email;
// set the value of the session variable 'education'
$_SESSION['seshEducation'] = $college;
// set the value of the session variable 'photolink'
$_SESSION['seshPhotolink'] = $photo;
// set the value of the session variable 'photolink'
$_SESSION['seshfbId'] = $id;
}
createSeshVariables($fbName,$fbEmail,$fbCollege,$photolink,$fbId);
?>
available.php
<?php
session_start(); // start up your PHP session!
header( 'Location: http://www.redacted.co/assets/php/searching.php' );
echo $_SESSION['seshfbId'];
//if i comment out header redirect the echo works here.
changeStatusToAvailable($_SESSION['seshfbId']);
?>
searching.php
<?php
session_start(); // start up your PHP session!
echo $_SESSION['seshfbId'];
?>
EDIT: after vardump i have found seshId and seshToken on the searching page. but the code used to create that is on tac.php. I have a feeling tac.php code clashed with session variables earlier
tac.php
$apiObj = new OpenTokSDK(API_Config::API_KEY, API_Config::API_SECRET);
$session = $apiObj->createSession( $_SERVER["REMOTE_ADDR"], array(SessionPropertyConstants::P2P_PREFERENCE=> "enabled") );
$seshId = $session->getSessionId();
$_SESSION['seshId'] = $seshId;
$token = $apiObj->generate_token($seshId, RoleConstants::PUBLISHER, null);
$_SESSION['seshToken'] = $token;
Resolved. As i suspected the opentok API clashed with my sesh variables because it invoked the session variables. i moved all the session variables to one php and problem solved.

Categories