PHP setcookie / cookies not working - php

I pulled this file from w3schools, it works perfectly fine through their editor but when I upload it on my hosting service it keeps showing up as "Cookie 'user' is not set". I checked my php.ini file and it seems like cookies are turned on, are there other settings that might be causing this problem?
<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), ""); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Thank you very much!

You have a line of HTML before your PHP code. I assume output buffering is off, so this line causes the response headers to be sent. Move the first line behind the PHP code.

You might not have cookies enabled on your browser. If you are using chrome, you can try the following steps:
Click the menu icon on the browser toolbar.
Select Settings.
Click the Show advanced settings
Click Content Settings
In the "Cookies" section of the dialog that appears, make sure Allow
local data to be set is selected to allow both first-party and
third-party cookies.
Click Close.
If you are using another browser, just google: "Allow coockies on [Browser Name]"

Related

Firefox does not accept that session variable is unset, while Chrome does

In my index.php I am including checkUser.php with the following code:
<?php
session_start();
echo("DEBUG_checkUser:" . $_SESSION['name'] . "<br>");
if (!isset($_SESSION['name'])) {
header('Location: denied.php');
} else {
echo("<span style='font-size: 12px'>Logged in as " . $_SESSION['fname'] . " " . $_SESSION['lname'] . " (" . $_SESSION['name'] . "). ");
echo("<a href='../POC/logoff.php'>Logoff</a>.");
echo("</span>");
}
?>
Then I have logoff.php with the following code:
<?php
session_start();
unset($_SESSION['name']);
//echo("DEBUG" . $_SESSION['name'] . "<br>"); //Notice: Undefined index: name in D:\XAMPP\htdocs\POC\logoff.php on line 5
session_unset();
session_destroy();
header('Location: ../POC/index.php');
?>
My expectation is, that by clicking Logoff, $_SESSION['name'] will be unset, and the user will be redirected from index.php to denied.php. This works as expected in Chrome (103.0.5060.114), but not in Firefox (103.0b9).
Functions session_unset() and session_destroy() are redundant IMO (indeed in Chrome it works without), I just added them to avoid getting answers, that I should add them.
If I comment out redirection to index.php and uncomment the display of $_SESSION['name'], I get an error for undefined index, so the session variable is correctly unset, but why Firefox does not accept that after redirection to index.php? And $_SESSION['name'], even though correctly unset in logoff.php, displays existing name, as the unsetting were not taking place.
I deleted all cookies for 'localhost' which I am using.
Cookie PHPSESSID is the same before and after logoff.
What should I do so this would also work in Firefox?
EDIT:
It was a cache issue, I set this to 0 seconds in .htaccess file and now everything works in both browsers:
<FilesMatch "\.(html|htm|php)$">
Header set Cache-Control "max-age=0, private, proxy-revalidate"
</FilesMatch>
So the question would be ... why did this work in Chrome before, when the cache for php was set to 60 seconds?
It makes no difference what browser you are using, the session is server-side. I think this is a browser cache situation. Open the Developer Tools in Firefox and disable the cache on the Network tab (see where).

Is it possible to get a cookie's new value after updating it using PHP, without a screen refresh?

I have used the standard PHP code to update the value of an existing cookie:
$cookie_name = 'user';
$cookie_value = 'Alex Porter';
setcookie($cookie_name,
$cookie_value,
time() + (86400 * 30), # 86400 = 24h x 60m x 60s
'/');
However, when I try to display the new value in the same script, the old value appears.
Here's the PHP:
if (isset($_COOKIE[$cookie_name]))
{
echo 'Cookie ' . $cookie_name . ' is set!<br>';
echo 'Value is: ' . $_COOKIE[$cookie_name];
}
else
{
echo 'Cookie named ' . $cookie_name . ' is not set!';
}
According to this SO query, a manual page refresh is necessary before the new value is displayed (Check Robert Rossman's answer):
Cookies set during a request will be available via $_COOKIE on the next page load/next request. They are not available in the current request.
You will probably have to store the value in some other variable if you need to access it in the current request.
I'd like to ask:
Why is the new value not available in the current request?
Is it a caching issue?
If it is cache related, is there a way to solve this?
Is there any other way to get the new value without a manual page reload?
In fact, if you go to Firefox's Developer Tools - Storage section, the new value is correctly displayed though the PHP script displays the old value (without a manual page refresh.)

How can i fix cookies in PHP?

i want to include cookies in my website in php but i don't know how to do this.
i've tried to include them with sessions but it didn't work.
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
i expected to keep me connected but it didn't. What else do i need to add in my code to make this work?
You're looking for setcookie()
Take a look at the PHP documentation for examples.
Edit:
To explain, before you can read a cookie, you need to set the cookie somewhere. You must call setcookie() before you output any information (e.g. echo or html before the php script tags) or there will be an error.
setcookie() also does not determine whether a user accepted the cookie. If a user has cookies disabled in browser, you would not be able to set or retrieve a cookie.
Since cookies can be manipulated, they tend to be a very bad place to store whether a user is logged in. Generally, sessions are better for that.

Why the cookie value is not being set after omitting or adding blank white space('') as the 'expire' parameter in setcookie() function?

I'm using PHP 7.2.0
I want to omit the expire parameter in setcookie() function while setting the cookie, so I tried below code and got Parse error in output.
<!DOCTYPE html>
<?php
$cookie_n = "user";
$cookie_value = "John Doe";
setcookie($cookie_n, $cookie_value, , "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_n])) {
echo "Cookie named '" . $cookie_n . "' is not set!";
} else {
echo "Cookie '" . $cookie_n . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_n];
}
?>
<p><strong>Note:</strong> You might have to reload the page to see the value of the cookie.</p>
</body>
</html>
Output :
Parse error: syntax error, unexpected ',' in ... on line 5
Then I tried with below setcookie() code but I got Warning and the cookie didn't get set:
setcookie($cookie_n, $cookie_value, '' , "/");
Output :
Warning: setcookie() expects parameter 3 to be integer, string given in ... on line 5
Cookie named 'user' is not set!
Note: You might have to reload the page to see the value of the cookie.
From manual consider below text about expire parameter,
If set to 0, or omitted, the cookie will expire at the end of the
session (when the browser closes).
So, according to this I tried the code but it's not working and generating parse error and notice. Please someone help me and correct the mistake I'm making in my code.
I also want to know, whether the cookie value set by omitting expire parameter value will be alive after closing the respective browser tab only and not the entire web browser?
Can I set cookies from Command Line? If yes, how? If no, why?
Thank You.

Why is session lost between SOME pages, not all?

I'm pretty new to PHP and I'm struggling with my webshop.
I have a drop down menu on my site with one menu option containing all product categories in the webshop. As long as I'm navigating between these categories my session is persistent and working fine (I'm putting products in a shopping bag and I can move to the cart and go through with the whole order). But if I go to a page in another drop down menu option "outside" the webshop (like the contact page) my session is lost. I have used pretty much the same template to create these pages, but they are of course more simple with mostly text content (apart from the cart that is always accessible from the top menu).
The first page outside the webshop drop down menu option is ok with the correct session id, but when I move to the second page the session is gone. It doesn't matter in which order I visit the pages. The first one is always working but the following ones are not.
What on earth can be causing this behaviour? On every page I start with this piece of code:
<?php
session_start();
?>
<!DOCTYPE HTML>
...
Further down I include the cart in the top menu:
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/includes/right-cart.inc";
include_once($path);
And in the included cart code I use this line for the session id:
$currSession = session_id();
Any ideas?
EDIT 1:
I tried to add some error logging and noticed something interesting. I now start my files with this (just to find out some more information):
<?php
phpinfo();
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
session_start();
// create session variable if it doesn't exist yet
if (isset($_SESSION['counter']))
$_SESSION['counter'] ++;
else
$_SESSION['counter'] = 1;
var_dump($_SESSION); echo "<br/>\n";
var_dump(session_id()); echo "<br/>\n";
var_dump(session_name()); echo "<br/>\n";
var_dump(session_get_cookie_params()); echo "<br/>\n";
?>
As long as I have the first row, phpinfo();, the session seems to be the same. But if I remove that line the session keeps renewing when refreshing the page...
EDIT 2
After a suggestion I tried to use a cookie to store a "session id" instead of a regular session. The code at the top of my page now seems like this:
<?php
session_start();
$currSession = "";
$cookie_name = "sessionId";
$cookie_value = "";
if(!isset($_COOKIE[$cookie_name])) {
$cookie_value = session_id();
setcookie( $cookie_name, $cookie_value, time() + (60*60*24*2), "/");
}
if(count($_COOKIE) > 0) {
$currSession = $_COOKIE[$cookie_name];
} else {
$currSession = session_id();
}
?>
But everytime I reload the page also the cookie value seems to change. I have tried different echo statements in the code to verify what happens but everything looks right (the cookie is created successfully, the isset function tells me that the cookie actually is set etc), but still the value in the cookie changes. Any ideas?
I finally solved the question so I thought I'll post the answer here in case someone else is having trouble.
I changed this line ("/"):
setcookie($cookie_name, $cookie_value, time() + (60*60*24*2), "/");
to ('/')
setcookie($cookie_name, $cookie_value, time() + (60*60*24*2), '/');
and suddenly it works! :-)

Categories