How to set a cookie in php? - 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.

Related

Read Cookie invalid with php

I can not read a cookie with php. Do not understand why.
It was created by this command: setcookie('cookie', '1', time() + 10000000);
The cookie is well established, I have looked in different browsers
The attempt by a read: echo $_COOKIE['cookie']; nothing prints and with var_dump($_COOKIE['cookie'] print NULL
It could be that the server will not let me read them?
Have you tired to set the $_COOKIE["cookie"] to a variable, and then made a echo on it, ex: $cookie = $_COOKIE["cookie"];
echo $cookie; Has happened to me a few times that it won't display the way you try to.
And of course, like #Kai Mattern said, you need the path
One possibility: You did not specify a path. Please check the cookie path in your browser and see if the default path hinders you to read the cookie.
A cookie with default set in yourdomain/somepath/page.php cannot be read by yourdomain/someotherpath/page.php.
Quick check would be to set the cookie path as /

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);

Having trouble making a PHP cookie stick

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.

Using cookies with php

I'm just trying to set and use a cookie but I can't seem to store anything.
On login, I use:
setcookie("username", $user);
But, when I use Firefox and the Web Developer plugin Cookies -> View Cookie Information There is no username cookie.
Also, when I try to access the value from a subsequent page using
$_COOKIE["username"]
It is returning null/empty
var_dump(setcookie("username", $user));
RESULT: bool(true)
and
var_dump($_COOKIE)
RESULT: specific cookie does not exist (others are there)
I have done some more testing...
The cookie exists after login (first page) but disappears when I go to another (2nd page) and is lost for good...
Are there any headers that must be present or not present?
http://php.net/manual/en/function.setcookie.php
Try setting the $expire parameter to some point in the future. I believe it defaults to 0, which is in the distant past.
Make sure that you are setting the domain parameter correctly in case the URL is changing after you go to another page after login. You can read more about the domain parameter on http://php.net/manual/en/function.setcookie.php
The cookie is probably expired because $expire defaults to 0 seconds since the Unix epoch. (docs)
Try
setcookie("username", $user, time() + 1200);
which expires 20 minutes after set (based on the client's time).
Use var_dump() on setcookie(..) to see what is returned. Also might do the same to $_COOKIE to see if the key is set.
Thanks everyone for the feedback... Aditya lead me to further analyse the cookie and I discovered that the path was the issue...
The login path was /admin/ and then I was redirecting back to the root...
Thanks all for your help and feedback!

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