Session-cookies: Weird Behaviour? Or Have I not understood something here? - php

Here is the piece of code:
session_name('somename');
session_start();
echo 'session name:'.session_name();
The above does print the session name as somename.
If I append the code below,
if(isset($_COOKIE['somename'])) {
echo "<br/><br/>"."Cookie somename not yet set";
}
else {
echo "<br/><br/>".var_dump($_COOKIE['somename']);
}
The output is always
Cookie somename not yet set.
Am I using the isset function wrong?
If I just append this:
echo "<br/><br/>".var_dump($_COOKIE['somename']);
Then, the output for the first time is:
session name:somename
Notice: Undefined index: somename in /path/to/file.php on line 12 NULL
If I refresh the page, then the output is
session name:somename
string(26) "367jr029jj17mdu5fgkfgiv0u6"
Isn't the cookie variable supposed to get set before the page content is loaded? or Have I not understood sessions/cookies?

Expanding on Jani Hartikainen's answer
isset() checks to see if $_COOKIE['somename'] is set.
First time through before cookies are set:
// $_COOKIE['somename'] is NOT set so skip to else
if(isset($_COOKIE['somename'])) {
echo "<br/><br/>"."Cookie somename not yet set";
}
else {
// $_COOKIE['somename'] is NOT set so you get an error.
echo "<br/><br/>".var_dump($_COOKIE['somename']);
}
Second time through after cookies are set:
// $_COOKIE['somename'] is set so show message
if(isset($_COOKIE['somename'])) {
echo "<br/><br/>"."Cookie somename not yet set";
}
else {
// $_COOKIE['somename'] is set so skip this part.
echo "<br/><br/>".var_dump($_COOKIE['somename']);
}
A more appropriate use of isset would be something like:
if(isset($_COOKIE['somename'])) {
echo "<br/><br/>".var_dump($_COOKIE['somename']);
}
else {
echo "<br/><br/>"."Cookie somename not yet set";
}
In the last example I use isset to determine if $_COOKIE['somename'] has been set. If so, then I dump it; otherwise, I show the message “Cookie somename not yet set”

Cookies aren't set into $_COOKIE until the browser actually sends them.
It works something like this:
Request 1:
Your script starts
$_COOKIE is empty
session_start()
Your script ends
-> cookies to browser
Request 2:
<- browser sends cookies in request
Your script starts
$_COOKIE contains your cookie
...

Related

XAMPP php executing both if and else parts

It is strange. My php code is executing both if and else parts. Following code starts where $_SESSION['abc'] is not set yet.
//echo $_SESSION['abc'];
if(!isset($_SESSION['abc'])){
echo "not showing this echo";
$_SESSION['abc'] = "new";
} else {
echo " why it jumps here, in XAMPP?";
}
My actual code was more complex so I did it simpler as above. The above code is not echoing "not showing this echo"; even when $_SESSION['abc'] is not set. If I comment out the statement $_SESSION['abc'] = "new"; it echoes "not showing this echo".
What I found out by now:
It is happening only in XAMPP, at production server same is working fine.
It happens when I make the else condition true in the if block. And that condition is setting a session variable.
I myself thought the code is executing twice or something but it is not.
And more importantly "if" condition is true, if you uncomment first line echo $_SESSION['abc'];, it will show undefined index error.
The weirdest feeling for me is, when it reaches $_SESSION['abc'] = "new"; in "if" block, it jumps to "else", ignoring the echo line before it.
Weird!! Am I missing something or it is a XAMPP bug. Yes, the code is working as expected, on production server.
EDIT:
I would like to add that only for this behavior I also reinstalled XAMPP (for the latest version).
And as to "how do I know if it sets session variable, while not echo the line before it", it prints echo $_SESSION['abc']; in else-block, but it shows undefined index error if I uncomment first line echo $_SESSION['abc'];
Code with echo line added in else-block.
//echo $_SESSION['abc'];
if(!isset($_SESSION['abc'])){
echo "not showing this echo";
$_SESSION['abc'] = "new";
} else {
echo " why it jumps here, in XAMPP?";
echo $_SESSION['abc'];
}
UPDATE 2018-06-03
I was doing the above code in Laravel. I tried the above code out of Laravel framework in a plain PHP file and it worked in XAMPP, as it should. So the new information is, this is not working in Laravel-XAMPP combination. Versions: Laravel 5.4 and XAMPP 7.2.5
NOW??
I'm not sure what you want to achieve. It looks like you are testing $_SESSION before you assign a value to your session key.
Do a print_r ($_SESSION) to become clear when which value is assigned. And which value is stored after you reload your session. You can also printout your statement to see the result like echo (!isset(value)) as an example.
session_start ();
print_r ($_SESSION);
if (!isset ($_SESSION ['whatever'])){
echo "not set";
print_r ($_SESSION);
}
else {
echo "set";
print_r ($_SESSION);
}
Also try to change the first statement to be true if set and assign your new value in the else block
session_start ();
print_r ($_SESSION);
if (isset ($_SESSION ['whatever'])){
echo "set";
print_r ($_SESSION);
}
else {
echo "not set";
print_r ($_SESSION);
$_SESSION['whatever'] = "new value";
}
Hopefully it helps to find the faulty place
Edit
Be sure to use
session_start()
at very first line
or to set
session.auto_start = 1
in your php.ini

The Cookie set is not detected

Hi guys i set a cookie using my script known as cookieset.php
setcookie("atid", $atid, time() + 60 * 60 * 24 * 365, "/", ".mydomain.com");
and it is shown in the browser
Name atid
Content 1234
but when i try to retrieve it like this from another script
echo 'value is: ' . $_COOKIE['atid'];
it gives the error saying
undefnied index: atid in.........
can anybody help me over this
setcookie("atid",$atid,time()+315360,"/");
// use
if (isset($_COOKIE['atid'])) {
echo "cookeies set ";
} else {
echo "cookeies not set ";
}
use mozila firebug / cookies to see cookies file
The $_COOKIE array is populated with information sent from the browser. The first time you request the file that calls setcookie - cookieset.php - the server sends the cookie to the browser, but at this time the $_COOKIE array was already populated without the cookie you just set.
The cookie will be available in subsequent requests until it expires.
To see the cookie in PHP, just do like this.
if (isset($_COOKIE['atid'])) {
echo 'Cookie found with value ' . $_COOKIE['atid'];
} else {
setcookie('atid', $atid, time() + 60 * 60 * 24 * 365, "/", ".mydomain.com");
echo 'Cookie was set. Please refresh to see it working';
}
The problem (from the error), seems to be that $_COOKIE['atid'] (depending on what line the error is at) is undefined - that means it has not been set, and seeing that you actually set the cookie, I am saying that its the atid that is undefined. Make sure you are getting it, check with isset()
Try this :
if (isset($_COOKIE['atid'])) {
echo $_COOKIE['atid'];
} else {
echo "No cookie Set";
}
And one more point :
it won't be available until the next page load or by doing the page request again.
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

setcookie(); does not set cookies

I have following problem, I am trying to set cookies without any success. setcookie(); function returns true so it looks like it setting cookie however when I am trying to access it on the same or following page I get error 'Undefined Index....'
<?
session_start();
ob_start();
echo setcookie("order",$_SESSION['cart'],time()+3600,'/',NULL);
//added to see if Cookie is set
echo "<br/>";
var_dump($_COOKIE);
exit();
if($_GET['paypal'] == 1){
header("Location: /paypal-express-checkout/process.php");
}else{
header("Location: /insert_order.php");
}
ob_end_flush();
exit();
?>
next page follows like this
<?php
session_start();
include_once("../includes/inc_config.php");
include_once("../order.php");
include_once("config.php");
include_once("paypal.class.php");
#region POST
if(!isset($_GET['token'])) //Post Data received from product list page.
{
//Mainly we need 4 variables from an item, Item Name, Item Price, Item Number and Item Quantity.
if(!isset($_COOKIE['order'])){
exit();
}
$paypal_data = '';
$ItemTotalPrice = 0;
$order = unserialize($_COOKIE['order']);
print_r($order);
exit;
You are setting the domain value to NULL. Try leaving the NULL away:
echo setcookie("order",$_SESSION['cart'],time()+3600,'/');
OR set it to your domain:
echo setcookie("order",$_SESSION['cart'],time()+3600,'/',".yourdomain.com");
I would var_dump or print_r the $_COOKIE variable before I make a decision that it's not getting passed through. Holding that thought once you setcookie something gets registered into the $_COOKIE variable for sure.
I agree with the statements above since you only can access $_COOKIE on the next refresh but there is another way to do it to make your form or page more interactive.
I would register the cookie and use a php page refresh (display a working... div while thats happening) then come back to the page and try to do what you originally tried doing. Very basic but pretty much straight forward.

How to set comma separated values in cookies

when i try to set cookie in the following way the values show me in the browser for the cookies are like this
cookie name -> recent and value 1%2c2
where 1 and 2 are my get parameters and %2c i dont know what is this i wants , in place of %2c
if(!empty($_GET['c']))
{
$c = $_GET['c'];
if(isset($_COOKIE['recent']))
{
$c=$_COOKIE['recent'].','.$c;
setcookie('recent',$c);
}
else
{
if(setcookie('recent',$c))
{
echo "yes";
}
else
{
echo "no";
}
}
}
echo $_COOKIE['recent'];
Note that the value portion of the cookie will automatically be
urlencoded when you send the cookie, and when it is received, it is
automatically decoded and assigned to a variable by the same name as
the cookie name.
http://php.net/manual/en/function.setcookie.php
http://www.php.net/manual/ru/function.urlencode.php

php session problem

I think this code should echo "first" in first usage and after refresh it should echo timestamp,but it will show first every time,where is my problem?
I set cookie permition on always.
if (isset($_SESSION['TestSession']))
{
echo ($_SESSION['TestSession']);
}
else
{
echo "first";
$_SESSION['TestSession'] = time();
}
Have you placed
session_start();
at the top of your page?
To start a session, first session_start() should be called. Otherwise $_SESSION won't be set, and you will initialize it every time.

Categories