Having trouble making a PHP cookie stick - php

I'm trying to create a temporary login system for a site. I'm using cookies rather than a database as it is merely for FED testing but for some reason my cookies are not sticking :(
I know I'm posting fine because the header function works
if ($_POST['login'] == 1) {
if (($user=="name") && ($pass=="secret")) {
setcookie("seeker", "1", time()+3600);
header('Location: ../index.php?');
} else echo '<i>Incorrect username/password.</i>';
}

Try a full cookie setting with a larger expiry value:
setcookie('seeker', 1, time()+86400, '/', '.example.com');
The path setting may be the reason. If you're setting the cookie in a script in example.com/subdir/script.php, then the cookie will using /subdir as its path, and not show up for scripts running in different directories.

You should also consider using PHP Sessions. It will set the cookies for you automatically.

Related

Codeigniter, xampp cookies not setting

I'm using the codeigniter with xampp on a windows 7 PC.
I'm trying to use codeigniter's built in cookies, but I can't seem to get my cookies to set/stay. I know that the cookie code is going off, it's just not actually saving.
Here's the cookie code:
$this->input->set_cookie('userID', $userID, time()+259200, 'http://localhost', '/');
After running this and on every page, I've included print_r($_COOKIE); to see any/all cookies that are being set, but nothing shows up.
Is there something I've missed?
According to the docs:
The expiration is set in seconds, which will be added to the current
time. Do not include the time, but rather only the number of seconds
from now that you wish the cookie to be valid. If the expiration is
set to zero the cookie will only last as long as the browser is open.
So your code should be like this:
$this->input->set_cookie('userID', $userID, 259200);
Also i recommend you to set domain name and cookie path in the config file.
Here's the solution for anyone else that runs into this problem:
Cookies cannot be created on localhost, you'll need to use http://127.0.0.1 instead.
Go into CI's application/config/config.php and change any references to localhost you might have and change them instead to http://127.0.0.1 and do the same for the cookies. Set the following variables as well:
$config['cookie_domain'] = "127.0.0.1";
$config['cookie_path'] = "/";
Then to store the cookie: $this->input->set_cookie('userID', $userID, 259200);

PHP Cookies works well on localhost, but it's not working on live server

Note: This issue is already solved,
finally I found that it's not cookies
problem, the problem is on
unserialize() function. The serialized
cookie which being the parameter of
that function must be stripslash-ed
first.
Hi there, I have a problem here about PHP Cookies. I'm using PHP Cookies to save user preferences. I've tested my code on my local machine (localhost using XAMPP). Everything's works very well, including the cookies. But when I uploaded it to the live server, the cookies not working at all. It seems that the setcookie() function do not write the cookie value. I've tested by echo-ing the cookie value both on my localhost and on my live server. $_COOKIE[] value on localhost is showing but not with the one in the live server.
I thought maybe it's related to the $expire time zone like the one's in this post http://anupraj.com.np/index.php/php-cookies-not-working-php-cookie-tutorial-and-scirpt/14 . But then I realized that I've set the cookies to expire in 1 month, not only in one hour like on that blog post. So I think that's not the case.
This is the content of setting.php
<?php
$defaultSettings['default_post_to'] = 'both';
$defaultSettings['timesince_style'] = 'simplify';
...
$defaultSettings['display_geo_info'] = 'true';
$defaultSettings['enable_javascript'] = 'true';
if(!isset($_COOKIE['settings'])){
setcookie("settings", serialize($defaultSettings), time()+3600*24*30);
header('Location: index.php');
}
$setting = unserialize($_COOKIE['settings']);
?>
And this is content of index.php
<?php
/*
ini_set ("display_errors", "1");
error_reporting(E_ALL);
*/
session_start();
require_once("settings.php"); // Settings files
require_once('varlib.php'); // Get all possible passed variable
require_once('auth.php'); // Check for channel login status
// If inputbar form submitted
if( $_POST['inputbox'] ){
...
}
else{
echo "SETTING COOKIE: <br/><br/>";
// This print_r is only showing the $_COOKIE value (which is stored on $setting) on localhost but no on live server
print_r($setting);
switch( $com ){
...
}
}
?>
I've search about it everywhere (Google, stackoverflow, asking friends on twiiter/FB) still no solutions
I hope some body could give me the solution here
Thanks :)
Look at both path and domain parameters for the setcookie function.
Reference: setcookie # PHP docs http://php.net/manual/en/function.setcookie.php
Try this to set your cookie:
if ($on_localhost) { // change this
$domain = '.localhost';
} else {
$domain = '.webhoster.com'; // change this
}
setcookie(
'settings',
serialize($defaultSettings),
time()+3600*24*30,
'/', // this is the path
$domain // this is the domain
);
Good luck!
While applying solutions we get forgot the basic of Cookies.
Cookies are like headers. Like the headers, it should be sent before any output generates. then only it sets successfully. I have struggled a lot for this problem but when i went through the basics this problem got solved quickly.
this syntax will be enough to solve this problem...
setcookie(
'settings',
serialize($defaultSettings),
time()+3600*24*30,
'/' // this is the path
);
Try this:
setcookie("settings", serialize($defaultSettings), time()+3600*24*30, '/'); // added path
Also, could it be that serialize($defaultSettings) result is too large?
Try exit() after the Location-header.
A Location-header does not prevent a PHP-script from executing further instructions, maybe there is something executed after the header that causes the misbehaviour.
Probably your server time is not correct therefore Cookeis are not working on server.
Try this:
setcookie("settings", serialize($defaultSettings), 0);
Setting expiration to zero will fix your issue in this case. or update your server time.
Only initialize the ob_start() method before setcookie(). most of the developer ob_start() method include in config file.

How to set a cookie in php?

I set a cookie and then check if exist like this
if(isset($_COOKIE["fan"]))
{
//Do Nothing
}
else
{
$cookie = "yes";
$expire=time()+60*60*24*30;
setcookie("fan", $cookie, $expire);
include_once("../inc/functions.php");
echo fan_page();
}
When I test on my local machine, it works, but when i upload to production server, it doesn't work.
What am I doing wrong?
Thanks In Advance!
Marc
You probably need to set the domain for the cookie. Locally it defaults, but in production you may come across some issues if it's not set explicitly.
See the arguments for setcookie; http://www.php.net/manual/en/function.setcookie.php
I also suggest looking in your browser cache to see if it is being set.
A cookie set for one path/hostname may override a cookie set for another path/hostname even if it is newer.
For instance, if there is already a cookie set for "www.example.com" and you set one for "example.com", when you read back the same cookie you'll get the one that was set for "www.example.com".
Try setting the cookie for the more specific hostname.
This may be part of the issue.

Cookie won't unset

OK, I'm stumped, and have been staring at this for hours.
I'm setting a cookie at /access/login.php with the following code:
setcookie('username', $username, time() + 604800, '/');
When I try to logout, which is located at /access/logout.php (and rewritten to /access/logout), the cookie won't seem to unset. I've tried the following:
setcookie('username', false, time()-3600, '/');
setcookie('username', '', time()-3600, '/');
setcookie('username', '', 1, '/');
I've also tried to directly hit /access/logout.php, but it's not working.
Nothing shows up in the php logs.
Any suggestions? I'm not sure if I'm missing something, or what's going on, but it's been hours of staring at this code and trying to debug.
How are you determining if it unset? Keep in mind that setcookie() won't remove it from the $_COOKIE superglobal of the current script, so if you call setcookie() to unset it and then immediatly print_r($_COOKIE);, it will still show up until you refresh the page.
Try pasting javascript:alert(document.cookie); in your browser to verify you don't have multiple cookies saved. Clear all cookies for the domain you're working on to make to sure you're starting fresh. Also ini_set(E_ALL); to make sure you're not missing any notices.
Seems to be a server issue. My last domain was pretty relaxed on PHP error handling while the new domain shows every error. I'm using both sites side by side and the old one removes the cookie as it should.
Is there perhaps a timezone issue here? Have you tried setting using something farther in the past, like time() - (3600*24)? PHP's documentation says that the internal implementation for deleting cookies uses a timestamp of one year in the past.
Also, you should be able to use just setcookie('username', false); without passing an expiration timestamp, since that argument is optional. Maybe including it is confusing PHP somehow?
How you use cookies data in your application?
If you read the cookies and check if username is not false or not '', then setting it to false or '' will be sufficient, since your application will ignore the cookies value.
You better put some security in cookies value, to prevent user change it's value. You can take a look of CodeIgniter session library, see how CI protect the cookies value using hash. Unauthorized value change will detected and the cookies will be deleted.
Also, CI do this to kill the cookies:
// Kill the cookie
setcookie(
$this->cookie_name,
addslashes(serialize(array())),
(time() - 31500000),
$this->cookie_path,
$this->cookie_domain,
0
);
You can delete cookies from javascript as well. Check here http://www.php.net/manual/en/function.setcookie.php#96599
A simple and convenient way, is to use this additional functions:
function getCookie($name) {
if (!isset($_COOKIE[$name])) return false;
if ($_COOKIE[$name]=='null') $_COOKIE[$name]=false;
return $_COOKIE[$name];
}
function removeCookie($name) {
unset($_COOKIE[$name]);
setcookie($name, "null");
}
removing a cookie is simple:
removeCookie('MyCookie');
....
echo getCookie('MyCookie');
I had a similar issue.
I found that, for whatever reason, echoing something out of logout.php made it actually delete the cookie:
echo '{}';
setcookie('username', '', time()-3600, '/');
I had the same issue; I log out (and I'm logged out), manually reload the index.php and then I'm logged in again. Then when I log out, I'm properly logged out.
The log out is a simple link (index.php?task=logout). The task removes the user from the session, and "deletes" (set value '' and set expiry in the past) the cookie, but index.php will read the user's auth token from the cookie just after this (or all) task (as with normal operations). Which will reload the user. After the page is loaded the browser will show no cookie for the auth token. So I suspect the cookie gets written after page finish loading.
My simple solution was to not read the cookie if the task was set to logout.
use sessions for authentication, don't use raw cookies
http://www.php.net/manual/en/book.session.php

Why won't my cookie value change in PHP 5?

I have a website where the login info is optionally saved in a cookie (remember me checkbox at login) and when the user logs out, the value of the authentication cookie won't change to expire the cookie allowing logout.
The system does work correctly in both the dev and staging servers but for some reason will not work on our production server. We are running PHP 5 and Apache on all the servers.
Thanks.
Function to set cookie (minor edits for security):
function setCookieInfo($data,$expiry=0)
{
if($data === false)
{
//remove cookie!
$cookie = false;
$expiry = 100; //should be in the past enough!
}
else
{
$serial = base64_encode(serialize($data));
$hash = md5($XXX);
$cookie = $hash."---".$serial;
}
if($_SERVER['SERVER_NAME']=='localhost')
{
$domain = null;
}
else
{
$domain = '.'.$_SERVER['SERVER_NAME'];
}
return setcookie('Auth', $cookie, $expiry, $this->controller->base, $domain);
}
Posting some actual code might help, but I'll hazard a guess that it has something to do with the cookie domain being used.
Grab a traffic capture (e.g. www.fiddler2.com) of the SetCookie call that is intended to delete the cookie, and ensure that the Domain is valid and the expiration time/value is as expected.
Assuming you are using the PHP setcookie() function, make sure that the domain and path for the cookie are set correctly. Check PHP's documentation for the function for more information.
I might be able to tell you for sure if I had a little more info. Can you provide any more information without compromising too much about the project? How about the URLs of the dev, staging, and production servers, or at least examples of what they might be like?
Edit
Based upon the info you provided in your comment, I would recommend that you try using HTTP_HOST instead of SERVER_NAME. SERVER_NAME might be giving you a weird value depending upon your virtual server setup. Your path might not be quite right either - try a '/' and it should be available regardless of the subdirectory the user is in.
Also,
$this->controller->base
makes me think that you might be using CodeIgniter or Kohana. If so, you might consider using their cookie helpers.

Categories