When to use URL/session/cookie variables? - php

I do a lot of php and javascript, but I think this is relatively language-agnostic question. Are there any best-practices for when to use each of:
URL variables
SESSION variables
cookies
I understand the inherent limitations of what some of them can't do, but it seems like their use can overlap sometimes, too, and those instances are what I'm really asking about.
EDIT
Just to clarify: I'm pretty familiar with the technicalities of which method is stored where, and which the client/server can access. What I am looking for is something a little higher-level, like "temporary user settings should live in cookies, data state info should live on the server, etc..."
Thanks!

In general:
Use URL (GET) parameters for sending simple request parameters to the server, eg. a search query or the page number in a product listing.
Use session variables, as the name indicates, to store temporary data associated with a specific user session, eg. a logged-in user's ID or a non-persistent shopping cart.
Avoid using cookies when possible. Use them sparingly to store settings that are tied to a particular computer / user profile, eg. a setting such as "remember my user ID on this computer".

Sessions are stored on the server, which means clients do not have access to the information you store about them. Session data, being stored on your server, does not need to be transmitted in full with each page; clients just need to send an ID and the data is loaded from the server.
On the other hand, Cookies are stored on the client. They can be made durable for a long time and would allow you to work more smoothly when you have a cluster of web servers. However unlike Sessions, data stored in Cookies is transmitted in full with each page request. You should use cookie if you need longer logged-in sessions.
URL variables (GET) are open and can be seen by user. They are also useful as it allows the user to bookmark the page and share the link.

PHP embeds the session id directly into URLs when cookies are disabled. Then, the session id becomes a value accessible thru an HTTP GET variable.

Related

PHP: a way to check user login other than sessions

I am building a website and I am using sessions to check user login. I am wondering if there is any better and safer way to check user login. Because sessions are stored in the clients computer I think they are not very safe and easy to hack. Am I correct?How do big websites like facebook and twitter check if their user is logged in or not. I am new to PHP so dont say my question is too basic.
Sessions are not stored in the client's computer. You must be confused with cookies !
Sessions are definitely the way to go here.
No matter what you use as authentication, if the client computer is compromised, the client's method of authentication can be abused. So in this regard, any other way can only be as safe as sessions are.
All big sites use sessions, usually in conjunction with cookies.
I want you to first understand that Sessions are the only way you can identify a client.
You don't store sessions on either the client or server side. (If you want a secure system.)
First you need to understand the need for sessions, only then you can know what sessions are.
The internet is a stateless network of machines, each with their own identifiers. Most of the communication that we do while sending a request to load a page or visit various links are over the HTTP (Hyper Text Transfer Protocol).
HTTP is a stateless protocol, meaning any communication over this protocol is not required by the protocol to be stored on either the server or client.
Let us understand what this would mean, with an example:
Suppose you try to login to http://example.com
You fill the form, hit the send button.
All the data in your form is then sent to the server.
The server checks if the username and password received was right. If right, it sends you the secure data.
In your next call to the web server, you expect to be logged in. BUT, due to the stateless nature of HTTP, your server does not recognize you anymore.
You can make this work by sending your username and password with every call, but that would mean having to enter it every-time for each request.
Here comes the role of cookies, you set the username cookie as Joe and password cookie as qwerty. Now everytime a request is sent the cookies are sent by the browser and you are happy.
This scenario now again has a problem that you need to make an authentication check everytime on your server thus increasing the load on it.
Enter Sessions. Sessions mean states with some context. It may be a logged in user, it may contain preferences you have set or any other similar stuff.
Here, when the user is logged in the first time, the server generates a session ID. This session ID is then stored by the server in a DB, File or it's Memory (RAM) along with any other data like username of the person who is logged in, preferences etc.
The server response then contains the session ID, which may be in the form of a cookie, HTML5 session states or sometimes even hidden fields.
Now, every call the client makes, contains the session ID. The server then checks its session store for any valid sessions with the same ID and get into context therby giving a pseudo state-like mechanism to communications taking place over HTTP.
How long your browser stores this cookie can also be determined by the server while sending the cookie.
There are advanced techniques for further security like changing the session ID each time a call is made, but lets get into that only if you want me to.
Cheers! :)

User doesn't accept Cookies - login PHP

In my login code on my website, if the password & username are correct, I set a cookie to keep the user logged in.
I just heard from a user that he doesn't accept cookies automatically through his browser, and that that prevents him from logging in. That rhe cookie is not set.
Is there an easy way to counter that?
Tell me if you need the code I use.
It is possible to get this to work but often a real pain if you're using complex javascript/ajax.
In short, instead of storing the session id in a cookie, you embed it at the end of every link.
so
http://example.com/somepage.php
becomes
http://example.com/somepage.php?SessionId=ABC123
Unfortunately, while PHP can do this for you in some cases, it doesn't help with links you build yourself in javascript - and it only takes clicking a single link without the id to effectively log the user out
See this page for more information
As mentioned by Quentin in the comments, if you're not using a cookie to identify the browser which created the session, it's possible that sharing a link would share the session. This could be mitigated but not prevented by checking IP address/user agent but this would likely fail in large corporate environments with NAT and standard browsers

check/ Getting a session name with php

I have two Domain site (Exmp: A & B) and two database,
function site A is for a payment method, so if a custumer buy a product, it will be direct for login first and
The site B is as a frontpage (web interface) only.
My question is : how can I get or check the session value FROM Site A and show the session_name in my interface website when the user is open my web at the same time.
Thanks in advance
You're facing 2 problems:
The session-id is probably stored on a cookie, and the browser will not send a cookie originated from domain A to domain B (unless you're talking about the same domain).
Even if you're able to have the session-id on both domains, for the data to be persistent across 2 sites, you're gonna need a shared session storage configured.
Possible solutions:
Pass the session-id over the URL as query-string parameter (not recommended for many reasons and has to be configured accordingly in your php.ini).
As for the storage: the common approach is to use a database as your session storage provider (hence making is 'shared').
Also, you may reconsider the use of session altogether, if you're only doing basic redirection maybe you can pass the data over a regular GET or POST request.

Sessions or cookies?

I'm making a forum for learning mostly but hopefully it will have a couple of users some day.
What im wondering is should you use sessions or cookies for user authentication?
A cookie is a short piece of arbitrary data that the server sends through a header; the client stores it locally and sends it back on the next request. This mechanism can be used to maintain state from one request to the next even though HTTP itself is a stateless protocol. Cookies have two disadvantages: They offer only very limited amount of space (4 kB), and because they are sent back and forth in plain, a malicious client can fiddle with the contents before sending it back to the server, effectively making cookie data untrusted.
A session is a file on the server, identified by a unique ID which is sent back and forth between client and server so that the server can identify the client. The most popular way of sending the session ID is through the cookie mechanism, but it is also possible to pass the session ID through the URL (this is why you often see links that contain the URL parameter 'phpsessid'). This solves the two problems with cookies mentioned above: A file on the server can be as large as required, and the client cannot access the data other than through your own scripts.
Authentication is typically solved using cookie-based sessions; once authenticated, a new session is created, and the user ID is stored in it, and when logging out, the session is cleared and a new session ID is generated. Alternatively, you could store username and password in the session, and check them on every request.
Use a session.
A session is identified by a cookie, true, but not the same as storing user auth info in the client cookie, which is bad for security. A session cookie stores a guid or a hash in the cookie, then identifies the session (either database or file system based, depending on your server's php settings) based on that.
I recommend you store the primary key from your user table, not any other info, then look up the user info every time - this allows you to change their validation status, or security level on the fly while they are logged in; otherwise they will have to log out and back in before your administrative changes take effect for them - IE. you can't boot them.
Also, don't store the username/password, because that requires a less efficient query than by the indexed primary key (even if they are indexed as well).
They are essentially the same, working hand-in-hand. When you create a session..say through PHP, a cookie is created to store the session id too. On the other hand, you would create another cookie if you want to implement a "Remember Me" option to prevent your users from logging in every time.
I'm not a PHP expert, but Session and Cookie are related. In other programming languages you have the option of creating "Cookie based session" or "Cookie-less session". I'm not sure about PHP though so maybe you are referring to different concepts.
I feel using session is much more safe and easy then using cookies. The reasons are as follows:
1) In cookie we can only store a single piece of information, whereas in a session we can store as many information as we want.
2) Being stored on hard disk of user, cookies can be played with. Being a person interested in hacking, I have done that and gathered useful information about the user. Sessions cannot be used for such a thing.
If its a small amount of data (just one variable), I would use a cookie. Here is the code...
setcookie("cookie name", "cookie value or variable name", time+ 3600, "\");
this code sets a cookie that is readable for any of your webpages. It also will delete its self in one hour.
You can also see if the cookie exists like this (to see if it has deleted its self).
if (isset($_COOKIE['cookiename']))
{
}
to collect a value from a cookie...
$value = $_COOKIE['cookiename']; //makes a variable for this cookie for your program

Session Management and cookies-- the interaction mechanism

I am interested in knowing how session management and cookies work in PHP. I want to know their underlying mechanism, like how the browser interacts with the cookies, and how the cookies are used to validate the session data in the server.
Is there any web resources that allow me to learn that?
In PHP in particular, the standard way sessions work is that PHP generates a random session ID, and puts it in a cookie. (By default called PHPSESSID) This cookie is handled by the browser by saving it locally on the user's machine, and is sent with every request to the domain it belongs to.
This session ID is then used to refer to a data store on the server machine, by standard located in /tmp/ on an apache install on linux. This is where everything in the $_SESSION array is stored between requests.
As you may notice, this is only as safe as the cookie is, as there is no real authentication between the user and server that the user is the "real" owner of the session ID. This means that so-called "session hijacking" is possible by sniffing the cookie and inserting the cookie with the session ID on the attacker's machine. This can be used to take over an account on a webpage, and browse around it just as if you were the original user, because to the server you are.
There's also an alternate, even more unsafe, way of keeping the session alive that PHP supports. This is done by sending the session ID as a GET variable with every link. As you may notice, this means that if a user simply copy-pastes one of these links, he will be giving away all his credentials. =)
Further information could be found in the PHP manual.
From PHP’s Session Handling manual:
A visitor accessing your web site is assigned a unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL.
This unique id is a big random number that is stored on the server side to match it next time the client makes a new request. It typically goes into the /tmp directory.
A cookie is a bit of data that's associated with a HTTP address.
I.e.
1/ Browser requests www.google.com
2/ www.google.com response includes setting a cookie
3/ From this point on and as long as the cookie is valid (there's an expiry time associated with it), each subsequent request made by the browser to www.google.com/anything includes the cookie above
For details: http://en.wikipedia.org/wiki/HTTP_cookie
A cookie permits creating a session in the otherwise stateless HTTP protocol in the sense that it allows a client-server conversation to be isolated from other clients interacting with the server.

Categories