I'm building an autologin system using cookies, but one fundamental part of the functionality of the cookies fails: they are non-persistent over different sessions - or even pages!
In my login script, I set the cookies like this:
setcookie('userID', $userID, time()+86400); // (edited after replies)
$userID has a value.
Then I print the $_COOKIE variable and it says array(['base_usid'] => 1); So that's good, but when I click the home page and print the $_COOKIE variable there, it says NULL.
Does anyone see the problem?
Cookies should have a time value for how long they should stay... Check http://php.net/manual/en/function.setcookie.php
In other words, change it to: setcookie('userID', $userID, time()+86400);
to make it stay for a day for example.
Aah, I've learned something new about cookies :) They have a path and they are only available on that path (the directory they were created in). I created the cookies on /user/login, and then tried to read them on /news/index. Won't work.
In the past I used to build websites with all files in just one folder (I know it's bad), so I didn't know of this cookie property. Sorry, I should have read the manual better...
Thanks for your help!
P.s.: Typing print_r($_COOOKIE); won't speed up debugging. :(
Cookies need an expiration time. Otherwise they are by default destroyed when a user closes his browser.
Try this instead
setcookie("userID", $userID, time()+3600);
This will last for an hour. Make the number bigger to have it last longer.
To unset / remove it, change the plus + to a minus -
:)
If its still not working after you've set an expiry time (and you've checked the clocks on server and client are correct) then have you checked that the cookie is being sent? Sounds like the problem with 'headers already sent'. Which would also imply you have a problem with error reporting / logging.
C.
Do you want to learn how to build CMS systems and login managers, or do you want to build an app... ?
Hate to do this, but my answer is : don't build your own login system. Instead, go grab some framework like CodeIgniter, Kohana, or even drupal or Joomla. If you are building a login system as a learning experience to understand how cookies work/etc, then fine.. go ahead.. as long as you don't plan on putting it into some production site. Otherwise, grab a well tested framework and use it.
Related
For a period of time cookies were set on a single site with different values for the domain. This resulted in some people having cookies with the same name set for both .www.domain.com and .domain.com. The site is intended to be accessed as www.domain.com. This is accomplished with .htaccess rules.
The code will use .domain.com. now for the session.cookie_domain going forward.
The issue I am having is that when both cookies exist the browser sends both (both are valid). I see this is so in the headers and also when dumping out apache_request_headers(), however, when I dump out $_COOKIE I see just one of them.
["Cookie"]=>
string(74) "foobar=hkej4qdnq5kismiq3kl07qv6k2; foobar=ocvn7anlu2f2k2l37nl9ou3c21"
And then...
array(1) { ["foobar"]=> string(26) "hkej4qdnq5kismiq3kl07qv6k2" }
My session interface read($id) method is checking the old cookie and not the one we set on login.
What is the best way to address this? I am thinking I could just change the session name/identifier and start fresh. Or maybe evaluate the Apache headers in my read implementation. I have not found much that is relevant in searching the web, just a bunch of fluff from w3schools polluting the results, so I thought this might be a good one to post here.
I had the same problem and solved it by changing the session name.
PHP allows you to access the variable $_SERVER["HTTP_COOKIE"] and parse it yourself. This allows you to access both values, of the cookie, but you can still not tell apart the correct and the wrong cookie.
Unless those cookies contain really valuable data, I would not care about the old values and just start new.
Just change the session name from PHPSESSID to SITESESSID or something else of your choice. This will make sure that your application ignores the old cookie all together. If the lifetime of your session is 0, then its a SESSION Cookie(Gets deleted when the browser is closed), in such case you can change the session name back to PHPSESSID after a few days or a month of implementation since you will be sure that no one has the old cookie.
BTW: The browser isn't sending two cookies. It's just your old session cookie still alive.
As first, I know a lot questions are like mine, but I really don't know what I'm doing wrong...
As you might've guessed, I've a PHP script involving sessions.
Everything works like a charm, except setting the lifetime of my session.
I want to keep the session active for two weeks, but instead my (Chrome) browser says it's set to xpire after the browsing session (and it does). My PHP script:
session_name('DSWLogin');
// Naming the session
session_set_cookie_params(2*7*24*60*60);
// Making the cookie live for 2 weeks
session_start();
// Starting the session
It really doesn't work.
Thanks in advance,
Isaiah
Rewrite your code as
session_start();
setcookie(session_name('DSWLogin'),session_id(),time()+2*7*24*60*60);
Is it possible to run both session and cookie helpers? Cause I am trying and I can't get a cookie to set for the life of me, no matter what method I try either falling CI's docs to the letter and doing it there way or attempting to work with cookies through native php alone. Either way I try cookies will not set.
I have tried to set them like:
$this->input-set_cookie('AutoRemember', $mID.'-'.$hashbrown, $shortlife);
and
setcookie('AutoRemember', $mID.'-'.$hashbrown, $shortlife);
and I have tried to work with them like
echo $this->input->cookie('AutoRemember');
and
echo $_COOKIE['AutoRemember'];
the cookie helper is auto loaded just as is the session one, so they are loaded. session helper works like a charm, but the cookies I got nothing but a headache. All I want to do is set a cookie so I can have a "remember me" function on my site, and what should be a 5 minute deal to do, has taken me hours of various ways of passing it either by setting something for a view to pick up so it can set it in a view, or setting it in the controller and nothing.
Doesn't appear to be a browser issue either as both Chrome, and FireFox seem to not have a cookie getting stored anywhere.
So is it something with using both sessions and cookies or is codeigniter garbage when it comes to setting a cookie and kills the effort no matter which way you try.
Looking through some of the Expression Engine code (an app shipped by Ellis Labs that uses CI) they are calling the PHP native setcookie function in their set_cookie function, so perhaps this is the way to go.
Looks like there should be no problem having the cookie helper running in tandem with the Session library. That said it's worth noting the Session class is calling setcookie directly rather than using the cookie helper (way to reuse code CI!).
In general, calling the PHP function setcookie should bypass any CI stuff and work no matter what, so if that isn't working maybe something else is going on. Best bet is probably to start with setcookie and try to get that working.
Check the return value from setcookie, if it's false output has already been started and that's why it isn't working; could be the same issue you're running into trying the CI cookie helper too.
Firstly, please don't dismiss this question - I'm aware it's an ugly situation but hey, real life isn't pretty.
I'm developing an extra section to a web app that's written in asp.net, but in php - it's mostly done (the two parts don't really communicate with each other outside of a database - the integration is mostly just cosmetic.)
The only issue I have is detecting from the php part when the .net session has expired so that it logs the user out and redirects to the login page.
I believe the asp.net application is compiled, but either way I'm not allowed to alter it so I was thinking maybe the best thing to do would be to make a very small/simple aspx page that outputs true or false which I could call using curl from php (and passing the browser's cookies along.)
Would this even be possible? I'm not sure how session security works on asp.net eg whether one .net application can read another's session variables, but if it's anything like php then it'll be possible.
mypage.php --curl--> checksession.aspx --|
| |
<----------- true / false <---------------
So mypage issues a GET (with cookies from browser) to checksession using curl, checksession simply returns a true or false (or something like that) and mypage redirects to the site's login page if that's false.
The authentication for the php side is already sorted out and is separate to this issue.
So really, what I need to know is can I have just a simple .aspx file that does this check, and if so where would I go to to find out how to program such a simple page? If it's just a line or three, please could you let me know what those lines would be (I'm sorry I've never done any .net stuff..)
If this isn't possible, then if you don't mind, could you provide some alternative solutions? Thanks!
-- EDIT --
After spending most of the day with this problem, I'm now thinking that using php at all to get around this is a bad idea. There's actually two levels of authentication involved (one is normal HTTP request/response login type thing, then there's the .net session) - on top of that I totally missed the point that obviously these sessions are almost certainly going to be backed up by the IP of the users browser which I'd have to spoof or something coming from curl as that'll be running on the server.
So I think I'm going to use jQuery somewhere in the header of my page to check and redirect as required...somehow :/
-- EDIT 2 --
Ok, so the javascript way has suited my needs pretty well - obviously it's not a secure way of doing things, but fortunately in this case it's ok as this is just an app used on the intranet (and the shoddy way they authenticate users is terrible anyway.)
There are multiple ways here. First of all, the cookies alone won't do much, because the session can be expired in ASP.net even though the Cookie is still alive.
ASP.net supports multiple SessionStates, of which two are common:
In Process - here, the Web Server (Usually IIS) holds all Sessions in memory. If the IIS Service is restarted (Happens by default every 24 hours, not just when the system restarts!), All Sessions are wiped (that's why the cookie alone does not help). This scenario is default I believe and thus very common in single-server environments
SQL Server - here, the session data is stored in a SQL Server database. This isn't used that often though.
State Server. This seems really uncommon, so I'm omitting it.
Scenario 2 is your best bet, because you can just read the session id from the cookie and query the SQL Server database for the session info.
in Scenario 1, your approach is the correct one: You need help from the ASP.net Application, which can be a .aspx page. Make a request from PHP passing in the session cookie and check Session.SessionID and Session.IsNewSession to make sure the ID Matches and IsNewSession should be false - otherwise, ASP.net just recreated a new Session.
You may have to interact with the Session from the ASP.net page to activate it (Session["PingFromPHP"] = true) which may interfere with the ASP.net Application if your key (the name in the []-brackets) has the same name.
If the ASP.net Application is compiled, put the .aspx.cs file that serves as the code behind into a folder named App_Code, this should allow you to run it.
Hope that gets you started.
I don't know php but If both app are on same domain you should be able to read the ASP.Net session cookies and determine if it has expired or not., because cookies are bount to domain instead of web app using it and so browser will surely give the cookie with the request.
This maybe isn't the right answer to this question.. but I found a fairly easy (slightly ugly) fix which was a bit of luck really..
I created a page called checksession.aspx and asp.net (or the iis app) automatically redirected that page to the login page if the session had expired. Using this with curl I can now just check whether I get a 302 redirect and if so I know that the session has expired.
Woot :)
I have a site which does a few ajax calls on page load. For some reason, CodeIgnitor is inserting 4 sessions (I'm assuming one for each ajax call) as you load the page. I'm storing the sessions in the database.
I'm pretty sure there should only be one session per browser. Firefox seems to generate only one; other browsers seem to create a whole bunch of sessions. Multiple sessions for the same user are giving me some serious authentication problems.
Why is this happening? How can I stop it?
I know the discussion took place while ago, but somebody might find this useful.
By now I've used CI session without storing its data in database. Today I decided to give it a try and immediately run across the same problem: CI was generating new session in every page load.
I checked my server time, timezone, my cookie etc. - everything I could find as a tip on forums - with no result. Then decided to debug the CI Session class myself.
Long story short, it turned out that my user_agent field in my session table was too small - VARCHAR 50 - which cuts the original user_agent string - hence CI doesn't find my session and generates onother one. I just increased the user_agent field size to 200 and everything works like a charm.
I forgot to mention that I use Mac OS X Lion.
Again, hope this will help somebody.
Check the date / time on your client OS, and on your server.
I know its too late, but maybe someone finds this page while looking for the answer...
I think it happens because CI sets an expiration time on the cookie containing the session id and if the time difference between the server and client is higher than the expiration time the cookie gets old and the server will generate a new session for the client on every request. Never took the time to figure out the exact mechanism, but happened to me several times, and this fix always worked.
I've found this topic with same problem: on every page CI generates new session. Possible solution: remove underscored from site name ( NOT "my_test_site.com", but "my-test-site.com"). At least, this helped in my situation.
Check your config.php file and make sure the cookie options are properly filled out. If they are not it cant track the user and it will gen a new session on every page load.
Check the date / time on your client OS, and on your server.
I had the same situation and confirm the solution as a fix
$config['cookie_domain'] = "example.com";
Use your domain name in this snippet.