PHP can't remove cookie that was set by JavaScript - php

Is it possible to remove cookie that was set on front via JS with PHP?
I'm doing this:
*FRONT (JS):
if ($.cookie('myCookie'))
{
console.log('Cookie.. :( ');
}
else
{
console.log('Yaay! No cookie!');
$.cookie('myCookie', '123');
}
BACK (PHP):
if (isset($_REQUEST['removeCookie']))
{
setcookie("myCookie", "", time()-3600);
unset($_COOKIE['myCookie']);
}
Result:
Seems like it's a mistery

You can't force the browser to delete the cookie file. You can, however, delete the contents of the cookie and expire it. Which is exactly what you're doing with your code above. I would probably tweak it slightly:
setcookie('myCookie', '', 1, '/'); // no need to calculate one hour ago.

If client time is wrong, setting cookie expire with time() function may not work as expected.
To unset cookie try,
setcookie('myCookie', 'blah blah', 1);
Source: A Comment in php setcookie docs

It would depend on the users PC deleting the cookie after the timeout. Personally I wouldn't trust that. I'd set the cookie to an empty value, or set it to DELETED then in your test code check if it is set and then check if the value is not blank or not DELETED

To completely remove cookie from browser by PHP, Try this code
$name = 'exists_cookie';
unset($_COOKIE[$name]);
// Set empty value
$blank = setcookie($name, '', time() - 3600);

Can someone run up this code on a test machine I'm a tad confused as to why cookie can be "unset" but cannot be value changed or expired etc in php it seems like setcookie() isn't working at all.
<script type="text/javascript" src="jquery.js"></script>
<script src="jquery.cookie.js"></script>
<script>
$.cookie('myCookie', '123' ,'/');
console.log("Created myCookie");
</script>
<?php
echo $_COOKIE['myCookie'];
//Comment/uncomment below as required
//setcookie("myCookie", "BLAH", time()-430000);
//$_COOKIE['myCookie'] = "BLAH";
setcookie('myCookie', '', 1, '/');
echo "<br />unset myCookie";
echo "<br />".$_COOKIE['myCookie'];
?>
<script>
console.log($.cookie('myCookie').length);
if ($.cookie('myCookie').length>0)
{
console.log('Cookie exists ');
console.log($.cookie('myCookie'));
}
else
{
console.log('Yaay! No cookie!');
}
</script>
You seem to be able to create a php <> JS cookie mismatch ie: 2 cookies called exactly the same but storing different data.

Related

Cookie warning alert doesnt dissapear on first click

I created this Cookie alert bar for my site, it works as intented. But you need to click the close link twice to close down the warning for some reason that I cannot figure out.
I use this following function to check if cookie exists or not.
function checkIfCookieExist($cookieName) {
if(isset($_COOKIE[$cookieName])) {
return true;
}
else {
return false;
}
}
if cookie does not exist, and the cookie get parameter exists and equals 1 I create a cookie
if (!checkIfCookieExist('cookieConfirmation') && isset($_GET['cookie']) && $_GET['cookie'] == 1) {
$cookieName = 'cookieConfirmation';
$cookieValue = 'Cookie confirmation';
$cookieDuration = 86400 * 30 * 3;
setcookie($cookieName, $cookieValue, time() + $cookieDuration);
}
Prints out the cookie bar, links to index with a get parameter for the cookie
function renderCookieBar() {
echo('
<div id="cookieBar">
<p>blabla cookie, cookies on this site yo</p>
I understand, close this box!
</div>
');
}
Calls function to print out cookiebar at given place in my html code
if(!checkIfCookieExist('cookieConfirmation')) {
renderCookieBar();
}
I appreciate any answers or help,
Cheers!
When you set the cookie in the header, the cookie is not directly present; means: the cookie is available up on the next page hit.
Check the manual: http://php.net/set_cookie
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array. Cookie values may also exist in $_REQUEST.
You can either
1. Set the cookie and immediately reload the page
Set the cookie and force a browser refresah by using header("Refresh:0");.
if (!checkIfCookieExist('cookieConfirmation') && isset($_GET['cookie']) && $_GET['cookie'] == 1) {
$cookieName = 'cookieConfirmation';
$cookieValue = 'Cookie confirmation';
$cookieDuration = 86400 * 30 * 3;
setcookie($cookieName, $cookieValue, time() + $cookieDuration);
header("Refresh:0");
}
2. Use Javascript
When setting the cookie with JavaScript it is directly available from the browser. You may also rewrite your script, so the JavaScript sets the cookie and removes the notification bar.
There are many solutions (also here on SO) how to work with cookies in JavaScript easily. If you are using a JavaScript library like jQuery you also have plugins handling the cookies.

Cant create cookies when website is online

when i try to create a cookie with PHP they are not saved when the website is online.
When i'm on the localhost, its all okay.
For example:
setcookie('user_register', 'username', time() + 3600, '/');
How can i troubleshoot this? Is there any config in cpanel to disable cookie creation ?
Thankyou
You say it works on localhost, which alerts me to think that you have placed the setcookie below output like this for example:
<?php
// top of file
Echo "saving cookie";
setcookie('user', 'username', 3600, '/');
?>
This may work on localhost but will always fail on a real php server.
Setcookie is a header and must be placed before any output as stated in the manual http://php.net/manual/en/function.setcookie.php
To make the code above work you need to chaange place of the echo and setcookie so that it first sets the cookie and then outputs the text:
<?php
// top of file
setcookie('user', 'username', 3600, '/');
Echo "saving cookie";
?>
Then to read the cookie you need to go to a new page or refresh the page.
Cookies can't be set and read at the same time in php.
So to complete the code we can do like this:
<?php
// top of file
If($_COOKIE(['user']){
Echo $_COOKIE(['user']);
}Else{
setcookie('user', 'username', 3600, '/');
Echo "saving cookie";
}
?>
Now you can set the cookie and read it on the same page if you refresh the page.
Cookies are used next time you visit the page. So there are 3 general solutions: 1. Save it to cookie and for first time, just echo POST variables instead of COOKIE. Code will look like this:
setcookie('user', $_POST['user'], time()+3600); // notice time() function
setcookie('pass', $_POST['pass'], time()+3600); // you cant use absolute value here
if (!isset($_COOKIE['user'])) echo $_POST['user'] . ' ' . $_POST['pass'];
else echo $_COOKIE['user'] . ' ' . $_COOKIE['pass'];
, but if you really want to store password in cookie (very bad idea), then at least hash it. Code with hashing could look like this:
setcookie('pass', hash(whirlpool/*algorithm*/, $_POST['pass']/*text*/), time()+3600);
, then when you check the password, just hash it and compare hashes.
You cannot send and receive cookie in the same request. Here is a modification you should try
if(isset($_POST['user']) && isset($_POST['pass'])){
setcookie("user",$_POST['user'],3600);
setcookie("pass",$_POST['pass'],3600);
header("location:".$_SERVER['PHP_SELF']);
}
if(isset($_COOKIE['user']) && isset($_COOKIE['user']))
{
echo $_COOKIE["user"] . " " . $_COOKIE["pass"]; // This is line 28
}
However, it advisable to use sessions instead. Start by going through PHP_SESSION

Why doesn't my cookie get set

Im trying test the cookie that are set in my browser, earlier cookieid was given inside the url(mydomain.com?cookieid=1234). now im trying to set a cookie by calling the script which sets it. when i load the script known as proceed.php, i want that to go on and set the cookie as i have written. but it does not set the cookie as i intend
proceed.php
<?php
$cookieid = 1234;
include('bin/setcookie.php');
?>
setcookie.php
<?php
include_once dirname(__FILE__).'/../Lodread.php';
$cookieid = isset($_REQUEST["cookieid"]) ? floatval($_REQUEST["cookieid"]) : 0;
$project_id = isset($_REQUEST["projectid"]) ? intval($_REQUEST["projectid"]) : 0;
if (isset($_SERVER['HTTP_REFERER'])){
$urlParts=parse_url($_SERVER['HTTP_REFERER']);
if (isset($urlParts['query'])){
$vars = parse_str($urlParts['query']);
if (isset($vars['cookieid']) && floatval($vars['cookieid']) > 0 ){
$cookieid = floatval($vars['cookieid']);
}
}
}
if ($cookieid) {
if ( ! isset($_COOKIE["cid"])){
$cid = ($project_id?"$project_id:$cookieid":$cookieid);
setcookie("cid", $cid, time() + 60 * 60 * 24 * 365, "/", ".mydomain.com");
header('Location: '.Config_Reader::readProjectConfig('Cookie')->base_url.'/set2.php');
}
}
?>
This is sample, try like this.
How to Get the Contents of a Cookie:
Cookies set for a page can be retrieved from the variable $_COOKIE['cookie_name'] where 'cookie_name' is the name of the cookie you set earlier.
For example, if you wanted to display the value of the "userlogin" cookie, the following code should do the trick.
echo "Welcome back to the site" . $_COOKIE['userlogin'] ;
Note that you cannot set a cookie in PHP and hope to retrieve the cookie immediately in that same script session. Take the following non-working PHP code as an example:
/* WARNING: THIS WILL NOT WORK */
setcookie ( "userlogin", "anonymous", time()+60 );
echo "Value of userlogin: " . $_COOKIE['userlogin'] ;
Set Cookie without "mydomain.com".
use this:
setcookie("cid", $cid, time() + 60 * 60 * 24 * 365, "/");
now you check cookie set.
Try it without specifying the domain when using the setcookie function. Also, I would recommend passing $cid directly to your header function since the cookie value can't be retrieved within the same php script right away. Then finally you can see if the cookie is set for future use by using $_COOKIE['cookie_name'] in a separate php script to get the cookie's value.

Can't make users login for long period of time

I have this platform which you can login and do your tests (this is a test link): www.mf.pt.la
I can't understand why this isn't working... first I tried this on top of my config.php file:
ini_set('session.cookie_lifetime', 864000);
ini_set('session.gc_maxlifetime', 864000);
Than I tried this with a cookie:
$year = time() + 31536000;
if($_POST['remember']=="1")
{
setcookie("remember_me", $_SESSION[LOGIN_USER], $year);
}
elseif($_POST['remember']=="")
{
if(isset($_COOKIE['remember_me']))
{
$tendays = time() + 864000;
setcookie("remember_me", $_SESSION[LOGIN_USER], $tendays);
}
}
None seem to work because after 30mins/1h user is logged out! :(
This is very frustrating because inside this website users are usually getting in a out more than once per day, and having always to login is making me lose users actually! :(
EDIT 1:
Ok, so let's see where we are at this point.
After a lot of tests, I have noticed the problem was that I was trying to save an array directly into the cookie and it doesn't work like that. I have searched a lot and created a very simple cookie with name "test" and content "text" and it worked, so if what was working I did created a cookie!
Then I searched for a way to put it working all together on the same cookie instead of save one cookie for each information I needed.
So this is the conclusion. To create the cookie, this is what I've made:
$cookie_name = "remember_me";
$userinfo = $_SESSION[LOGIN_USER]['user_id']."_".$_SESSION[LOGIN_USER]['user_type']."_".$_SESSION[LOGIN_USER]['name']."_".$_SESSION[LOGIN_USER]['email'];
if($_POST['remember']=="1"){
setcookie($cookie_name, $userinfo, time() + 31536000, '/');
}else{
setcookie($cookie_name, $userinfo, time() + 864000, '/');
}
And to call the cookie this is what I have made:
if(isset($_COOKIE["remember_me"])) {
$usercookie = explode("_",$_COOKIE["remember_me"]);
$_SESSION[LOGIN_USER]['user_id'] = $usercookie[0];
$_SESSION[LOGIN_USER]['user_type'] = $usercookie[1];
$_SESSION[LOGIN_USER]['name'] = $usercookie[2];
$_SESSION[LOGIN_USER]['email'] = $usercookie[3];
}
So far, it seems to work, but... let's see if in some more hours the login is done automatically after I enter the website again.
EDIT 2:
Just noticed that spaces are saved into cookie as + and # as %40
EDIT 3:
FINALLY! I did it and here's what I did in order to help future users:
First, let's start by creating the cookie. I inserted a new colum in my users table to save a token, and assigned that token as an encription in MD5 to a variable, like this:
$tokenuser = md5(uniqid(rand(), true));
Once the table was updated, we must create the cookie, and here it is:
$cookie_name = "mfrm";
if($_POST['remember']=="1"){
setcookie($cookie_name, $tokenuser, time() + 31536000, '/');
}else{
setcookie($cookie_name, $tokenuser, time() + 864000, '/');
}
For those who didn't understood that "if" condition, that's simply to check if the user have selected the "checkbox" in order to be remembered "forever" (one year in this case).
So far so good, the next part was the one that was "try and error" until I finally did it! You should put this code BEFORE your headers, because otherwise it might not work and will probably give you an error:
if(isset($_COOKIE["mfrm"])) {
$usercookie = $_COOKIE["mfrm"];
}
So, this way your variable $usercookie now has the content of your cookie (the unique token we created).
"Later" on your code, you simply do a call to your database, check for which user that token is valid and then just asign user_id and all other things you want in order for user to have his login. :)
I hope whoever sees this can solve the problem, I did a LOT of Google search before I finally get this working.
My suggestion is, do a lot of "print" and "echo" in PHP so you can see where is your problem, if needed stop your code by inserting sleep(2); (where 2 means two seconds)
Good luck! :)
This won't suffice, cookies are saved in user's browser, so every time she connects, you check her cookies and and set set up her session accordingly.
Hope this helps
=== EDIT ===
This may help you: http://www.pontikis.net/blog/create-cookies-php-javascript
Let's say that the user ID is '12345', and he is logging in
You set the cookie with:
setcookie('user_id', '12345', time() + (86400 * 30), '/');
Then, then if the user logs in tomorrow, and his session has expired, you check if his user_id exists in DB from the cookies:
if(isset($_COOKIE['user_id'])) {
// check the user_id in DB and create session if exists
}else{
// User has no cookies, then he has to login
}
Hope this makes sense.
This is a very simple example, so of course, do not just put a user_id in your cookies, but a more rigorous form of authentication, like the last session id and a token you'd have generated.
=== EDIT2 ===
Is 'remember' the name of a checkbox? Because in which case, if it is not checked, $_POST['remember'] is not set. So instead of checking the value of $_POST['remember'], you should check if it is set or not
Assuming that 'remember' is the name of a checkbox:
$year = time() + 31536000;
if(isset($_POST['remember']))
{
setcookie("remember_me", $_SESSION[LOGIN_USER], $year);
}
else
{
if(isset($_COOKIE['remember_me']))
{
$tendays = time() + 864000;
setcookie("remember_me", $_SESSION[LOGIN_USER], $tendays);
}
}

strange result when trying to increment a n php cookie

can someone please how what hell this
cookie stops at 2 ?
<?php
if (isset($_COOKIE["count"]))
{
$cookie = ++$_COOKIE['count'];
}
else {
echo "Welcome guest!<br>";
setcookie("count", 1, time()+3600);
}
ECHO $cookie;
?>
thank you all
$cookie = ++$_COOKIE['count']; is only called once. If $_COOKIE[count] has a numerical value, $cookie will store that value plus 1.
Also, the following is not strictly correct:
echo "Welcome guest!<br>";
setcookie("count", 1, time()+3600);
You cannot call an echo before a header. I recommend you change it to this:
setcookie("count", 1, time()+3600);
echo "Welcome guest!<br>";
You cannot change cookie value by incrementing $_COOKIE[xxx], you have to use setcookie() function for that. This will work:
<?php
$cookie = isset($_COOKIE["count"]) ? $_COOKIE["count"] : 0;
setcookie('count', $cookie + 1, time()+3600);
ECHO $cookie;
You cannot update a cookie that way. However you can overwrite it.
See setcookie for more info.
If you set a cookie, it won't retrieved until the next request and so the data won't be present in $_COOKIE.
So setting a cookie and accessing it cannot be in same instance. You need to redirect or refresh after setting it.
Simply use setcookie() to increment.
to increment you place the ++ after the string, not before it.

Categories