Sessions and cookies - php

I currently have a website that allows my visitors to login via a simple script i've pasted together and wrote. Currently I only use sessions to keep visitors logged in. Are there any advantages to adding cookies to my website to store user logged in status?
Or is there a better way altogether?
using PHP

If you are using PHP sessions then you are using cookies. PHP stores session ID in cookies and the session data to a file on the disk on your web server.

#Ramiro Gonzalez Maciel he said he has made that script, he doesn't need frameworks to take as examples. Frameworks usually have scripts wrapped up and well placed.
To respond that question:
I usually store in cookie some md5 strings that are combined from his md5(password) and his username so I'll know next tim he enters my website that is was logged in so I wouldn't make him login again
my example:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
// sql and escape stuff witch will return 1 if he has entered a valid login
if($sqlreturn == 1){
// do login
$wraplogin = md5($username."-".md5($password)."-".SECRET_KEY); // I always define a define('SECRET_KEY', 'mysecretkey'); in global file.
// now you can store that $wraplogin in cookies and remember his login. Next time he enters the website, you read that cookie, compare it with what you have in your database and let him in.
}
?>
Now I know that is not the best example, but I've personally used it in very large websites (>500.000 users) and none has hacked in yet :)
That's the advantage in cookies for the login part.
Best of luck.

The web frameworks ( Java Servlets and others ) usually use cookies to identify sessions; the other usual option is URL parameters. So assuming you're using any web framework, it's probably already using cookies to store the session id. The Web Framework will use this ID to identify the Session object in every request. Although cookies survive server restarts, since they're stored in the browser, Session objects usually don't unless you've configured Session persistence.
If you want to users to "auto login" as in the usual "rembember me" option many web sites implement, you would have to persist Session objects if your framework provides that. Or implement a similar system, using cookies to store a "logged in token", and checking that token when the user access the system to auto-log them or send them to a login page. ( Edit: like Mihai proposes in other answer )
If you want to implement your own method, I suggest checking how the popular web frameworks implement this, specially the security and privacy aspects of storing user data in cookies.

Related

Is Ajax token "more" secure if session is ONLY started on admin login?

After hours of research to make an Ajax request secure, I came accross PHP Session. I generate a token and pass this value to the session like this:
session_start();
$token = "test".rand(1,10);
$_SESSION['token'] = $token;
This is obviously a test scenario. My token is encrypted and generated differently. I use this session to make an XMLHttpRequest from a form to an external file in the same server which echoes some text I only want admin[s] to see. The file which contains the text has this url http://127.0.0.1:8888/demo-site/content looks like this:
session_start();
if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
if (#isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] == "http://127.0.0.1:8888/demo-site/ajax") {
if ($_GET["token"] == $_SESSION["token"]) {
echo "Successful";
}
}
}
As you can see from the code above, it first checks if it is an AJAX Call, then where the request is coming from and lastly it compares the tokens. I pass the token to the external php file in form of link parameter, hence $_GET["token"] from http://127.0.0.1:8888/demo-site/content?token=xxx.
I used to check if the user is logged in, and if true then check if the user is an admin and if that is also true, then echo the content. Can it be that, if the php code which does session_start() and its respective form is ONLY showed to users logged in as admin, this adds an extra layer of security.
I mean, if a hacker wants to access the external file's content, must he first crack the admin's password, and afterwards the token?
I am assuming this given that no session is started if nobody is logged in as admin and simply the content does not show. I do not want to rely the security of this file based on a token, but the user must be an admin as well.
Or can the hacker access the file's content if he knows what token is, regardless if the user is logged in as admin?
With this I refer to, that the hacker knows the token but there is no session_start(). I have giving this a lot of thought but I am not sure if this assumption is correct.
I think you are overcomplicating things. PHP has good Session Security - see http://php.net/manual/en/session.security.php and implement the settings recommended there. "session.hash_function" is particularly important, and means that session tokens can't be 'cracked' or guessed.
In general, brewing you own security systems in place of generally used ones is a bad idea. Adding new layers of security on top of PHP Sessions is probably unwise unless you really know what you are doing.
First, use SSL. This will secure your data in transit. Next, don't use GET for tokens or passwords, as this exposes them to proxy and server logs. Once an Admin signs in, they receive a secure PHP Session token as a cookie. This cookie is transparently used by PHP to get a session using session_start(). In your session variables, you have defined, for example, $_SESSION['admin']=1, and this means this session is an Admin. When accessing Admin data, check that $_SESSION['admin']==1.
The Client is responsible for their own security. You can't do anything about this (except use something dynamic like MFA). What I mean is: if the Client's computer is compromised, any hacker can key-log sign in credentials, or read cookies etc, so anything you do server side will be hackable. You can add layers and layers of security, but it is bloat.
So can this be hacked? Yes, if the hacker has access to the Client computer. But then everything can be hacked. If there is no breach on the Client computer, SSL protects the communications.

Allowing sessions on multiple sites

I am working on a site that has a login API. So when people login on my site, they will automatically be logged in to other sites.
Is their way by which a session can be setup so that other websites can use it? If not, is their any other solution?
One way - you can store your session values in database, and can use in other sites. :)
Example:-
let suppose if my site is deployed on multiple servers and end user might be redirected to different servers accordingly to traffic, then it would be good to save the session values in db.
Yes. It's possible using in example Redis for the session storage. You should look for configuring php sessions to use custom storage. Here is php man for this http://php.net/session.customhandler
What you want to do is probably using a cookie that is spread over your whole domain. This cookie can then be linked to a session. I'm currently working on something like this on Symfony2.
As example:
login.mydomain.com
application.mydomain.com
etc.mydomain.com
login.* will obviously contain my login logic + forms etc. This will also contain an API which the other applications can verify the cookie to. My Application will first check if the user is logged in. If not, it will check if it has the required cookie. If it does not, it will redirect to the login.* login page.
If it does have the cookie, it will validate this in my login.* API. Expired > redirect to the login page, if not it will return the required info of that user and "login" to my application.
The only problem I have at the moment is storing the session. I use mcrypt to encrypt the contents and store it in mysql (cookie_id, cookie_contents). I have but 1 problem, it doesn't automatically purge the expired sessions, I still have to find a solution for this.
What you are basically looking for is Single Sign-On (just a guess, but I think accurate).

Android to use cookies or sessions?

I am working on an android app that is actually gets user data from android device and then to put it on the server, like to get user name, password, email for registration purpose and then user login to access the app menu (to see list of products, search for products and to add his/her own product details in the list). So using cookies and sessions would be a good idea for my app. Cookies can be blocked by the user and sessions every time to login to access.
But as i am totally new to this concept of cookies and sessions so it would be good to ask a question here before i have to start, that which one should i use cookies or sessions ?
The user can not block cookies. Cookies are simply headers that you will send in each request.
Cookies are easier to handle on the server side. You will simply use $_SESSION["variable"] to get/set any variable for the user. It will simplify your life on the server. However, I think the main drawback will be maintainability and administration of sessions. For example, if a user logs in again on a different device and you want the first session to be invalidated. It is not very straight forward.
If you want to use sessions, you will probably save them in a table on some database. You will need to fetch the session details when you need them. This is sort of extra effort. Yet, database sessions provide some kind of administration capabilities straight away.
I prefer database sessions for what is stated above and some other reasons. However it is up to you

Proper security for communication with DB in Web App

I really have a lot of questions about this specific area. But basically I just want to know how to create the most efficient and secure php session communication method. I have read so many websites talking about this and they don't seem to agree or relate to my current situation.
My problem is that I don't know how to create login, sessions, cookies, registration etc. properly to match a high security level. This is my idea so far.
1. PHP SESSIONS
I will start a session after the login has been made. I know that there are different ways for me to handle these but at the moment I have created a session variable like so $_SESSION['user'] which lets me store the users e-mail address during the session. Then I have a problem when the session is ended with the server. That leads me to the next property.
2. COOKIES
With cookies I would be able to store the e-mail address and the hash encoded password and then be able to recreate a session based on these login information.
<?
session_start();
require_once('config.php'); //retrieved from the servers include folder specified on the apache server.
// if session is closed that means that there wouldn't be stored a session variable called 'user' anymore.
if ($_SESSION['user'] == '') {
// if the cookie hasn't been set..
if ($_COOKIE['user'] == '') {
// ... close the session and return to the login page
session_destroy();
header('Location: login.php?err=4'); // err=4 means session ended
} else {
// We don't know wether the user has logged in using e-mail or username, so that's why we connect using either email or username.
$sql = 'SELECT * FROM login WHERE (email = :user and password = :psw) or (username = :user and password = :pass)';
$statement = $conn->prepare($sql);
$statement->bindParam(':user', $_COOKIE['user'], PDO::PARAM_STR);
$statement->bindParam(':psw', $_COOKIE['psw'], PDO::PARAM_STR);
if ($statement->execute() && $row = $statement->fetch()) {
$_SESSION['user'] = $_COOKIE['user'];
} else {
// Failed to retrieve data somehow.
}
}
}
?>
But then I have read that the session_id() also is a cookie stored value, which will be the same every time I recreate the session. So I actually don't have to match the values to the server again, cause I can simply start session again and continue from where I left.. But I see this as a security break, since that if the session_id() has been retrieved by somebody else, they will be able to connect using same session_id() etc.
3. I also need to use the values from other domains
I know that it is possible to use the same login-details from another website e.g. Facebook, Google etc. I want to be able to reuse the same login for all the domains I am working with, but how do I secure that only mine (registered) domains can have access to the login information, and not other sites?
4. Is there another secure way?
This is actually my question. I am not sure that what I have done or planned is highly secure, and I definitely don't think that my newbie experience is good enough to create a login-secure database connection. So I would like to know if anybody could link me to the official page of the right way to store and use login details in PHP in the most efficient and secure manner.
PHP sessions are the way-to-go when you want to handle logins in PHP. To do this in a save manner you should make sure that your session data is stored on your server and the client only has a session_id in a cookie.
Every time you have a security-level change (login, logout etc), you should regenerate the session id to ensure more safety (old stolen session id's will become unusable). You should also make the session cookie http_only, which will make it impossible to steal the cookie using JavaScript.
From a security perspective I would recommend you to never use cookies to store sensitive information. Information stored in cookies are not save, they are stored on the clients computer and can be altered or stolen.
Google and Facebook make logging in to all kinds of websites possible using openAuth(2). I'm not sure whether that would be usable for you, but cookies will only be accessible by at most one domain.
I would recommend using PHP sessions, they are secure if you handle them correctly. If you are not really sure how to do that you could take a look at some good PHP frameworks. I know from experience that the Laravel framework has a good login-handler.
Sessions already use cookies to keep the session. If you configure it properly, you can keep sessions open indefinitely, if that's what you want to do (unless the user deletes cookies, but then your cookie-based solution won't help either). Anything you build yourself with cookies will probably be less secure than that, so I wouldn't bother with it. Properly configure the session settings of course.
Reusing information across domains is a complex field. If they are all backed by the same database, just let the user log in on any site. You will need to manage separate sessions (read: user will need to log into each site separately, but can use the same user/password) or built some pretty complex cross-domain session sharing (hint: you probably don't want to). If you want to go for a more complex solution (e.g. because your domains don't share a central database), google "single-sign on" and prepare for hours, days and weeks of reading.

Do i login using cookies or sessions in a login system?

Do i login using cookies or sessions in a login system? I've seen examples using sessions and cookies so i am confused! Can someone please explain this?
What do most sites use? love to know!
Thanks in advance;-)
Sessions - in most cases - use cookies to store their session id so its pretty much always a case that you are using both. Most sites will use sessions as cookies are inherently insecure as data is stored at the client side where as session data is stored on a server. It is largely a matter of security and what data you intend to store but since its so easy to modfify cookie data then you should never really trust anything within cookies.
Login with Sessions because they are safer than cookies in that user's don't have direct access to your cookies.
BUT, when you use sessions, you are also using cookies, so in fact you are using both...
ex:
//query to get username from database
$_SESSION['user_id']=___
$_SESSION['username']=____
DON'T store passwords or anything sensitive in sessions or cookies
A session is your server or applications idea of a person. In default PHP, when you create a session, a cookie is sent to the browser for storage. Every time the browser makes a request, it will send the cookie along and the server will lookup the information it has associated with that cookie. Sessions are good for storing user settings or server information because the user only ever sees the session key.
With cookies you can set a preference independent of the user or session at your site. Like the style of the page or whether this is a shared browser. This information will be sent with requests from that browser, so can be accessible from server scripts. The bonus with cookies is that javascript can use their values for processing without backend support (for static pages), and that the user can change them themselves.
Good advice above should be followed: put nothing in cookies you wouldn't want anyone to see.
Not only can the user see them, anyone with access to the users computer or the network connection between you and the user can see them.
It is a bit of a minimalistic answer but here goes:
- If your login system has a "remember me" feature, it very likely uses cookies but not sessions
- If not, it uses cookies and sessions (because sessions use cookies as per said in above posts)
Hope it helps

Categories