I know how to set PHP cookies in an array but can I clear it without a loop?
For example I'm setting these four cookies
// set the cookies
setcookie("cookie[four]", "cookiefour");
setcookie("cookie[three]", "cookiethree");
setcookie("cookie[two]", "cookietwo");
setcookie("cookie[one]", "cookieone");
// after the page reloads, print them out
if (isset($_COOKIE['cookie'])) {
foreach ($_COOKIE['cookie'] as $name => $value) {
$name = htmlspecialchars($name);
$value = htmlspecialchars($value);
echo "$name : $value <br />\n";
}
}
OUTPUT:
four : cookiefour
three : cookiethree
two : cookietwo
one : cookieone
To clear the cookies, i use the following loop
if (isset($_COOKIE['cookie'])) {
foreach ($_COOKIE['cookie'] as $name => $value) {
setcookie ("cookie[".$name."]", "", time() - 1);
}
}
Are there any way I could clear the cookies without a loop? Thanks in advance
No, you pretty much need to loop through existing cookies as the way to delete/expire a cookie, as you have in your code via setcookie, is one cookie at a time.
Could try
if (isset($_COOKIE['cookie'])) {
setcookie ("cookie", array());
}
or even
if (isset($_COOKIE['cookie'])) {
setcookie ("cookie", array('one'=>'','two'=>'','three'=>'','four'=>'',));
}
if you need the indexes
Related
I am maintaining the code for an eCommerce website, they use a highly modified version of osCommerce v2.2 RC2. Was noticing an issue where the session isn't started for a new user until they visit the 2nd page of the site.
Looking at the code, before starting the session, it tries to set a cookie. If it detects the cookie it starts the session. Something along this line:
setcookie('cookie_test', 'please_accept_for_session', time()+60*60*24*30, $cookie_path, $cookie_domain);
if (isset($_COOKIE['cookie_test'])) {
session_start();
...
I found an article here that talks about a situation like this, it states:
The first time you only tell the browser to set the cookie, at the time, there is no cookie data in the request header (which could get from $_COOKIE).
Which explains why it takes two page loads for the session to be started. One to set the cookie and one to get notification from the browser that the cookie is set.
My question is, is there anyway around having to go through two page loads to detect the cookie was successfully set on the users browser?
I found this question that didn't really answer my question completely. The highest voted solution was:
setcookie('uname', $uname, time()+60*30);
$_COOKIE['uname'] = $uname;
Which may make it "work" but it doesn't truely tell me that the script was able to set a cookie successfully.
I also found this question, that suggested accessing the headers_list to find the cookie information like so:
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');
Which, again, doesn't seem to be verifying that the cookie was set successfully. All this appears to do is search the headers being sent to the browser for the cookie value.
The only solution I can think of is to redirect on the first visit after setting the cookie. Is there any other way?
Here is the answer:
<?php
function set_cookie($name, $value) {
if (!isset($_COOKIE[$name]) || ($_COOKIE[$name] != $value)) {
$_COOKIE[$name] = $value;
}
setcookie($name, $value, strtotime('+1 week'), '/');
}
// Usage:
set_cookie('username', 'ABC'); //Modify the value to see the change
echo $_COOKIE['username'];
I am trying to unset the cookies, I had earlier set as:
setcookie(session_name(),$sessionID,time() + 30*24*3600,'/');
setcookie('UserID',$result[0]['UserID'],time() + 30*24*3600,'/');
setcookie('UType',$result[0]['UType'],time() + 30*24*3600,'/');
setcookie('Username',$Username,time() + 30*24*3600,'/');
Logout File:
function unsetCookie() {
foreach($_COOKIE as $key => $value) {
// $_COOKIE[$key] contains the cookie name as expected
setcookie($_COOKIE[$key],'',time()-(40*24*3600),'/');
}
}
unsetCookie();
session_start();
session_destroy();
header('Location: '.$loginPage);
exit();
But after the redirect in the logout file, cookies are still not deleted. What could be the reason for this?
$_COOKIE[$key] contains the value of your cookie, not the key as that is $key.
So you would need:
setcookie($key,'',time()-(40*24*3600),'/');
Set the value to "" and the expiry date to yesterday (or any date in the past)
Try this code like that :-
setcookie("UserID", "", time()-(40*24*3600));
setcookie("UType", "", time()-(40*24*3600));
setcookie("Username", "", time()-(40*24*3600));
Is there a straightforward way to test whether a cookie has been set during the current request? I'm writing an extension to existing code, so I can't modify the current code to add something like $_COOKIE['something'] = $someValue;. Unfortunately, only setcookie is called, without the event being logged in any other way. I need to know before the client receives the headers, because I need to set the cookie if the existing code hasn't already done so.
Have you tried using isset?
if( ! isset($_COOKIE['something'])) {
$_COOKIE['something'] == $somevalue;
}
Here's my "brute force" solution for now. I'm hoping to find a better method, though. Note that headers_list() gets the headers that are going to be sent to the browser as part of the response, not the headers that were sent by the browser during the request.
foreach (headers_list() as $header) {
list($k, $v) = explode(': ', $header, 2);
if (strtolower($k) != 'set-cookie') {
continue;
}
$name = explode('=', $v, 2)[0];
if ($name == $cookieName) {
return true;
}
}
return false;
I have a requirement to access a sessionID variable passed through header. I need to verify the sessionID before process the request. Also please let us know how can i set a sessionID in request header. please help me to find a solution. Your help is much appreciated. Thank you
I have tried
$headers = apache_request_headers();
foreach ($headers as $header => $value) {
echo "$header: $value <br />\n";
}
Use this code:
foreach (getallheaders() as $name => $value) {
echo "$name: $value\n";
}
This will give all the information of header.
Here is more tutorial about getallheaders() function.
If you want to get only session id then use the below code:
echo session_id();
To set a session you can use,
session_start();
you can use GET method in 1st page to pass the id in header.
session_id($_GET['PHPSESSID']);
session_start();
You can extract the session id in another page by using session_id()
session_id() returns the session id for the current session
else it retuns the empty string, if there is no current session.
<?php
$id = session_id();
if(empty($id)) session_start();
echo "SID: ".SID."<br>session_id(): ".session_id()."<br>COOKIE: ".$_COOKIE["PHPSESSID"];
?>
Hope This helps.
I am trying to diagnose an error in my cookies, but the names of the cookies are not what they should be. Is there a way in PHP to print all the cookies that have been set by my domain?
Have you tried:
print_r($_COOKIE)
foreach ($_COOKIE as $key=>$val)
{
echo $key.' is '.$val."<br>\n";
}
<pre><?php print_r( $_COOKIE ); ?></pre> will do what you want. You might also try phpinfo().
echo $_COOKIE["cookie_name"]; // Print an individual cookie
print_r($_COOKIE); // Another way to debug/test is to view all cookies
You can display all cookies defined by running the following php function:
var_dump($_COOKIE);
if($_COOKIE) {
print_r($_COOKIE); //print all cookie
}
else
{
echo "COOKIE is not set";
}
As with any inputs, security practices should include filtering and validation. Since all cookies are strings, sanitize the strings:
var_dump(filter_input_array(INPUT_COOKIE, FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY))
PHP Docs: https://www.php.net/manual/en/function.filter-input-array.php
if($_COOKIE) {
foreach ($_COOKIE as $key=>$val)
{
echo $key.' is '.$val."<br>\n";
}
}
else
{
echo "No Cookies are Set";
}
This will check if any cookies are set, if found will iterate through each and print out the cookie name and value