How to properly "delete" a Cookie in PHP - php

I have created a PHP and Cookie-based Login and Logout system for the admin page of a WebApp I am working on. Issue is when I refresh the page more than 2 or 3 times when I am Logged In, the Log Out function doesn't work properly, and keeps me "Logged In" if I attempt to load an admin page after I have "Logged Out". I am not certain if this is a browser setting, or something I am coding incorrectly.
Login PHP Code:
setcookie("password","$thepassword");
Logout PHP Code:
unset($_COOKIE['password']);
setcookie('password', null, -1, '/');
Any ideas welcome. :) Thanks~

A few seconds of google search would save you the hassle of asking a question, thought its already been answered here before, check this
I would also mention that storing users passwords in a cookie is a crime! please use sessions for such an ocassion.

You can always assign the cookie a null value:
setcookie("user", NULL);
However, cookies tend to be a rather insecure way of storing user data. I strongly recommend using sessions in stead. Keep in mind that users can change the value of cookies, but not sessions. Then to log out you can use session_destroy()
Also, try refreshing the page after the cookie is unset.

I solved my issues by converting the script to use Sessions, and not Cookies.
Thanks for the advice guys. :)

Related

Stay logged in through a PHP discord oauth2 (cookie?)

I am working on a site that involves logging in through discord, which uses oauth2. I believe the login is controlled by the phpsessid cookie, from what i can tell. My problem is this cookie resets when the browser is closed, meaning whenever the browser closes, the user has to log back in.
I was wondering if there was a way to keep the session running even after closing the browser, or maybe a different method to keep the user logged in? I found the PHP function session_set_cookie_params() that could be useful, but I'm not sure how I can use this in my situation.
In order to store data even if you close the browser, you need to use cookies. With PHP, you need to use the setcookie() method.
Default example:
<?php
setcookie('yourCookieName', "yourCookieValue");
?>
Another example:
<?php
setcookie('yourCookieName', "yourCookieValue", time() + 365*24*3600, '/', '.yourdomain.com');
?>
I have added some parameters as time and a way to keep the cookie for all the website subdomains.
And then, if you can get the cookie with $_COOKIE['yourCookieName'].
You can try to use javascript to acces that cookie and then save it as a new cookie on your website,and then load it when the user connects.Look on w3school javascript cookies

Is it a good idea to `session_destroy()` when a site's user logs off or in?

I'm building a small website project and I am curious if there would be any reason not to do session_destroy() when a user wants to log off? What about just before logging in a new user? The site request a user to be logged in before interacting with the site in any way.
Yes it is. It's actually the common way to do so. If you want an example see the docs for session_destroy() there's a complete example with everything you need to do.
If you are using PHP's built in session management, then it is what you should do at each logout. This way you can make sure that a new user at the same computer can't reuse any saved data that has been stored for the previous user before.
An other way is session_unset, but that, unlike session_destroy does not delete all session data such as data in the session storage. More about the difference: What is the difference between session_unset() and session_destroy() in PHP?

The duration of the sessions

I am having issues with a website I am making.
I need to do a thing like "Facebook" (manage session in the session page, more sessions at the same time):
when the user login, I open a session, I give him a token and I store it in a MySQL database. And so far, everything is ok.
If the user login, and set "remember me", I open a session, I give him a token and I store it in a MySQL database. But, how can I set a "remember me"? Because if he close the browser, he lose the session token.
I think I explained myself, please help me. I can't find anything in the web! :(
Mabey you could use cookies instead of session.
so store the data inside a cookie and call it when needed.
Yry using session_set_cookie_parameters and set the cookie life time to whateer you want:
<?php
$lifetime=600; // set in seconds!
session_set_cookie_params($lifetime);
session_start();
?>

Cookie replay after logout php CodeIgniter

I have an application where the login and logout works correctly. Once the user logs out, and tries to access a page he needs authentication for, he is redirected to the login screen.
Where my problem lies is. If while I am logged in, if I copy the cookie values and save them on a file. After logout, I alter the cookie and add the same values, I get logged back in into the application as the same user.
On logout I have written a function that loops over all the cookies and deletes them.
My understanding is that cookies are both on the client and also on the server side. So if the cookies are getting deleted, they are getting deleted on both the sides and that the server would not recognize them after they have been cleared, even if the browser sends them back again(apparently that is not the case, i think).
The reason why I am doing this is because this is one of the points raised by our security auditor, and I need to get a way to fix this hole. (At this point doing https is not feasible)
I'd be happy if someone can give me pointers on how I can clear out the cookies on the server side as well, so, when the next time someone hits the server with the same cookie, it does not accept it as a valid cookie.
Edit:
I am using codeigniter sessions and tank_auth as the authentication library. At logout, the library itself calls
$this->ci->session->sess_destroy();
to be extra sure, I tried the following after a few attempts :
session_start();
session_unset();
session_destroy();
session_write_close();
setcookie(session_name(),'',0,'/');
session_regenerate_id(true);
My regular logout works, and if I try to access the page directly it does not open.
But if while I am logged in, I take my cookie, save it somewhere -- log-out successfully and replace the cookie with my older one, I get right back into the session.
Is there a way to stop this behavior -- Where the server side will not entertain a session after it has been destroyed. I also made sure that my server and php are on the same timezone (setting it with date_default_timezone_set).
Cookies are not stored on the server at all. Those are stored in the browser and then sent to the server in the request headers. You can easily find software and plugins for browsers that allow you to create/edit/delete cookies. For that reason you should never store sensitive information in cookies. Essentially what you want to do is store the user data in a session and then store the session name in a cookie. Usually this is done automatically in php when you use the function session_start().
If you are using Codeigniter, the php session functions are wrapped in a CI session library that is auto loaded on each page load. So instead of storing data in $_COOKIE you will want to get/set your data via the userdata method in the session library:
//in your controller
//save session data
$userdata = array(
"isLoggedIn"=>true,
"username"=>$_POST['username']
);
$this->session->set_userdata($userdata);
//get session data later
$isLoggedIn = $this->session->userdata("isLoggedIn");
if(!$isLoggedIn){
//if the user is not logged in, destroy the session and send to the login screen
$this->session->sess_destroy();
redirect("/");
}
Note that the code above is not tested and is only supposed to give you an idea on where to go. If the session methods aren't working for you, you may need to load the library in manually:
//in the __construct method of your controller:
$this->load->library("session");
You can find more information here:
http://ellislab.com/codeigniter/user-guide/libraries/sessions.html
and here:
http://www.php.net/manual/en/book.session.php
Thanks for you answers guys.
This is what I figured, later. I am not sure what was causing this but the sessions were not getting invalidated after trying everything. I moved the sessions on codeigniter to the database. Then the logouts started working correctly, where after logout if the 'stolen'/'saved' cookie was put in the browser again it would Not log the user back in.
So, thats what solved it.

The best way to create log-in realm in PHP

I can do login realm in PHP and the way that I do it is by setting a session variable and check whether that session variable is set or not. On every restricted page, I check whether a certain session variable is set (or is equal to a certain value). If not, then i will send the user back to the login page. Is this the best way to do it? Is there a more secure way to do it?
This is fine and normal. At the top of the page, you have a header that starts a session and checks whether the user is authenticated. When they're not, make them log in.
A-OK and secure so long as your session IDs are unpredictable, expire quickly enough, and you are using SSL.
If someone can guess your session IDs, they can hijack another user's login.
If you are not using SSL, an attacker can steal the session ID when the client sends it to you.
If your sessions never expire the ID can eventually be guessed.
There's a lot to think about when you're setting up a login system. Here are some questions you want to answer:
Security: You need to encrypt passwords everywhere they are stored (cookies, database, sessions, etc.). How will you do that?
Will users be able to post login to every page? Or will there be a centralized account page?
Is there a remember me feature?
How will users logout?
Do you have activation at your site? How will it work? How will you deal with various scenarios such as unactivated users trying to login?
Will you have login/form redirection? I.e., if a user goes to a page without logging in will you send them there after they login? What if they try to send a form? Will you resend the form.
You have the basic idea right, but the way you structure everything depends on those and other questions.
I've got a similar question on SO before, and here are the answers from security guys.
Put it short, you should think other things like SSL and password hashing, etc...
Hope this helps :)

Categories