Codeigniter, xampp cookies not setting - php

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

Related

PHP How can I set a default path to cookies

I'd like to know if there's anyway I can set default path to cookies, so I doesn't need to specify it on setcookie function call, I tried on php.ini file, but it's not working as I supposed.
When I check out my cookies on firebug, I get that: FireBug PrintScreen
I need both to be the same value, so if I put the code bellow on any file at "/loja", it works.
setcookie("PHPSESSID", $_COOKIE['PHPSESSID'], 0, "/");
But the problem is, I have the same code working on different areas, so I'm pretty sure it's something wrong on server side config.
I hope made myself clear, any insight about it would be great.
You're making a mistake by manipulating phpsessid directly.
Use session_name instead:
session_name("sessionExampleName"); //Use diferent names for each application
session_start();
To get or set a session id:
//Set:
session_id('newid');
session_start();
//Get
session_start();
$id = session_id();

Php cookie won't unset/delete - can't logout

So i've tried multiple other "solutions" to my problem (both on this site and others) and cannot find a solution that works for me.
I'm trying to set a cookie to log in my user and then on log out delete that cookie. Here is my code.
list ($check, $data) = check_login($dbc, $_POST['Username'], $_POST['Password']);
if ($check) {
setcookie('Username', $data['Username'], time() + 60*60*24*90);
header('Location: RedirectPage.php');
Which, checks the username and password have been entered on the login form (and accepted), If so, the cookie "Username" is set with the username drawn from the database, and a time equalling 90 days, and the user is then redirected.
This part works fine, it logs the user in as would be expected.
However in the delete part,
header('Refresh: 0;');
setcookie('Username', '', time() - 60*60*24*90);
unset($_COOKIE['Username']);
require ('RedirectPage.php');
redirect_user();
I delete the cookie in the same way it was set, as expected, removing any data and setting the time to a negative value, and then for good measure i run the unset cookie to ensure that it has gone.
Except, this doesn't work. setcookie (to delete) does not do anything, and unset cookie only works on the page after it has been run (in this case, index.php) and as soon as i click to another page, or refresh the page it "forgets" that the cookie has been deleted.
Now going into the Chrome inspect element to check the cookie i get
Username, "Value" (the withdrawn username), r3gamers.com (domain), / (path), 2015-02-03T13:45:00 (Expires/MaxAge), 19 (Size) and HTTP and Secure are both set as empty.
Watching the process after hitting the logout button, this cookie is never deleted. The only thing which can actually delete the cookie is overwriting it with a new cookie (logging in again) or deleting it through inspect element.
Any ideas? As far as i'm aware, i'm doing everything that should be done.
EDIT:
I'd also like to mention that when testing this on localhost, offline through netbeans this functionality does work. However when i upload the pages to godaddy for my website they stop working properly.
I found the answer. It's a stupid answer too. Here is the full code file i was using for logout.
<?php
require_once ('Connection.php');
header('Refresh: 0;');
if (!isset($_COOKIE['Username'])){
header('Location: LoginFunctions.php');
} else {
setcookie('Username', '', time()-60*60*24*90, '/', '', 0, 0);
unset($_COOKIE['Username']);
header('Location: index.php');
}
?>
The problem, which i can't show here, was that the opening php tag had a single line break on it, meaning that it started on line 2. Why it was like this initially i don't know, but that small error meant that it worked on localhost and didn't work on godaddy. How frustrating. At least i've fixed the problem now.
For future use, for those stuck with the same issue, apparently godaddy (or most hosting sites) require that any cookie adding, editing or deleting occur from line 1 onwards, therefore the php tag which includes the cookie must be on line 1, no html code can preceed this php tag, or any line breaks, the php tag has to start on line 1.
You do not set the path of your cookie, I assume you want it to be site-wide, so you should set the path to '/':
setcookie('Username', $data['Username'], time() + 60*60*24*90, '/');
And then, when unsetting it, try using 1 instead of time() - 60*60*24*90 (also still specifying the path), otherwise the expiration time of the cookie might vary depending on the user's computer clock:
setcookie('Username', '', 1, '/');
I think your problem really is the path not being set: http://php.net/manual/en/function.setcookie.php
If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.
The thing is, if you are in /logout/doit.php, and you try to set the cookie expiration time to a negative value, it will create a new cookie with the path '/logout/' and set its expiration time. (Instead of setting the expiration time on your site-wide cookie)

Unable to access cookie after page redirect

I am setting a cookie containing a vlue in this format and redirecting to another page via the PHP header function. Here's the code,
setcookie("myCookie", $cookieValue, time() + $cookieLife, "/"); // cookieLife is expiration time in sec
header("Location: $baseURL/index.php"); // $baseURL is "http://localhost/mysite"
The cookie is getting set within the browser. However, I am unable to access the cookie value in the redirected page, i.e., "index.php". I am trying to access the cookie value with a simple echo like this,
echo $_COOKIE['myCookie'];
However instead of the cookie value, I get the following notice,
Notice: Undefined index: myCookie in /path/to/my/site/index.php on line 1
I have set the cookie path to "/" after looking at other solutions but am still unable to solve this.
Any help much appreciated.
EDIT :
I am testing this on XAMPP server, and the "mysite" here is actually an alias for another location on my hard drive. Could this be causing this issue?
I assume your cookie gets removed or dissapears once you've left the previous page.
Check if time() + $cookieLife is the desired time you want the cookie to live. The PHP setcookie function tells me that your $cookieLife is the time in seconds that you want your cookie to live, so make sure that it's the value you want it to be.
Use an extension to check your current cookies (and alter them if you need to). This way you can check and make sure if the cookie is living as long as you want it to (you already mentioned seeing the cookie being set, but I will include this just in case + for future visitors).
FireFox Extension: Web Developer
Chrome Extension: Cookies

PHP $_SESSION not staying across localhost subdomains [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Allow php sessions to carry over to subdomains
Kind of complicated, but I've got 4 subversion repositories that I want to run side by side on my localhost for testing.
I set php.ini as so:
session.cookie_domain = ".localhost.com"
I setup my hosts file:
127.0.0.1 vader.localhost.com
127.0.0.1 luke.localhost.com
When I login, it sets the cookie correctly.
Name: PHPSESSID
Content: b0d3h7nh5ff40sms26q04oasq3
Domain: .localhost.com
Path: /
I set the $_SESSION variable on login:
$_SESSION['authorized'] = true;
Reload the page, the headers are correct:
Cookie PHPSESSID=b0d3h7nh5ff40sms26q04oasq3
Host vader.localhost.com
Referer http://vader.localhost.com/
But the $_SESSION variable is empty.
This all works fine if I remove the subdomain.
Thoughts?
EDIT:
Suhosin is NOT installed.
Also, someone asked for the full code for the session setting:
if (authenticate($dat['username'], $dat['password'])) {
session_start();
$_SESSION['authorized'] = true;
$_SESSION['username'] = $dat['username'];
$_SESSION['userType'] = findId('t_user', 'username', $dat['username'], 'userTypeId');
$_SESSION['userId'] = findId('t_user', 'username', $dat['username'], 'userId');
$_SESSION['contactId'] = findId('t_user', 'username', $dat['username'], 'userContactId');
array_push($reply, $reply);
$reply['authorized'] = true;
}
Found this answer from PHP Sessions across sub domains, it shall helps :)
I donĀ“t know if the problem still exists, but I just ran into the same
problem and solved it setting a session name before calling
session_set_cookie_params():
$some_name = session_name("some_name");
session_set_cookie_params(0, '/', '.some_domain.com');
session_start();
I have changed nothing in my php.ini but now everything is working
fine.
You might need to call session_write_close() to force a cookie to save before the script ends (or you redirect).
Check the default cookie storage place and see what is in the files. This is usually the /tmp directory on linux.
Stop storing cookies in files. Start storing them in encrypted cookies which will free you're server from the unneeded I/0 requests.

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!

Categories