0

I have read in a lot of places like, session_start() creates a cookie, session_start() creates a cookiethat under default configuration of php.ini session_start() creates generates a random sessionID and stores it in a cookie on the user's browser. However, I could not find any reference to this in php.net. Is there a place where I can find some proper documentation and internal working of this?

Secondly, I want to understand a sequential step by step process of how a simple login system would look like in PHP in conjunction with the above, i.e session, the sessionID generated and the associated cookie set by session_start(). Please help providing a step-by-step process of this flow, like :- (Assuming that user User1 is already registered into the system and now he is trying to access a page which needs him to be logged into the system)

  1. User1 clicks the URL hxxp://restrictedPage.php (for example)
  2. System checks and see that User1 is not logged in - meaning say system checks to see if there is a valid sessionID apparently in place here. (So what exactly would be checked ?)
  3. Since the check (which I need help with) in step 2 fails user is redirected to login.php (say for example) that has the login form.
  4. On the login form user enters username and password and submits the POST form.
  5. Server side - authenticateUser.php (say for example) verifies the $_POST['userName'] and $_POST['password'] with the db values. Let's assume that this checks returns true, i.e the username and password supplied by the user was correct.
  6. What happens now from here on? Where does the session come into picture and when is the cookie with the sessionID created? When is it sent to the browser?
  7. Now when the session is in place (which I need help with understanding how exactly) and the user comes to a landing page after the login, say, welcome.php which also has a link to restrictedPage.php and now when the user clicks on this link, how exactly is the session validated on the server? I mean the cookie holding the sessionID would be sent with this request, but where is it cross checked with the sessionID already present on the server? Is it done explicitly (like we do for validating username and password from db) or is it taken care of automatically by PHP?
GileBrt
  • 1,765
  • 2
  • 16
  • 27
qre0ct
  • 4,420
  • 6
  • 37
  • 73
  • See the source for internals: https://github.com/php/php-src/blob/71ad601deef5df51192788049838e6c3d7d88c5d/ext/session/session.c#L1487 – Piskvor left the building May 07 '14 at 16:05
  • Thanks for indicating the internals @Piskvor. I would appreciate if you could provide inputs on the second section of the question as well. – qre0ct May 07 '14 at 16:08
  • @geek_ji giveme a sec ill write you a complete login system, with full documentation for every step. – Lawrence Cherone May 07 '14 at 16:12
  • Why downvote, the question is ok, but it would be good if we could see any attempts. (own code, not linked) nvm i wrote an answer, i hope it helps – Dávid Szabó May 07 '14 at 16:14
  • @geek_ji I think your confusing something which is, the php session id is not **sent** to the client its **received** as part of the response headers, then the client/browser resends the id with subsequent requests. session_start will set the headers as soon as its called, this is why you cant call session_start after output. – Lawrence Cherone May 07 '14 at 16:19
  • @LozCherone The ID is SENT to the client via a response. So it is SENT. The visitor gets a response which contains a cookie, this cookie contains a value, which is the visitor's SESSIONID. BUT you can use sessions without using COOKIES, but this makes the sessionid shown to the client several ways. – Dávid Szabó May 07 '14 at 16:25
  • @newboyhun: I have not seen a cookieless session system in PHP for at least ten years; while still technically possible, it's a massive hassle (and contains several security pitfalls, as you're exposing the session ID everywhere) – Piskvor left the building May 07 '14 at 16:27
  • 1
    @Piskvor I didn't say to use it, I say DON'T use it, i just mentioned it. – Dávid Szabó May 07 '14 at 16:28
  • @newboyhun its not sent like the server makes another TCP/IP connection to the client and sends it using a socket, its sent as in the response packet the client receives, which is what I said. – Lawrence Cherone May 07 '14 at 16:44
  • this may be useful: [the-definitive-guide-to-form-based-website-authentication](http://stackoverflow.com/questions/549/the-definitive-guide-to-form-based-website-authentication). – Ryan Vincent May 07 '14 at 17:29

2 Answers2

1

The session (and its cookie, if none exists yet) is created right at the beginning, when you call session_start(); it is sent to the browser with the response, via the response-header Set-Cookie

A valid session ID only says "This browser has requested a page from me before", nothing more: PHP checks if a session by that name exists (see the source to see how exactly this happens, but this is not interesting for normal use), and deserializes it into $_SESSION.

It is up to you to couple this with authentication, authorization and identification - usually, the login functionality checks username and password, and if correct, sets a session variable "this is user 1234":

if ($is_login) {
    // in real use you would check the username & password against a db
    if ($username == "Piskvor" && $password == "123456") {
        $_SESSION['user'] = 789;
    } else {
        // bad username or password
        $_SESSION['user'] = 0;
    }
} else if ($is_logout) {
    // logout this user from session
    $_SESSION['user'] = 0;
}

Then in a restricted section, you can check the session variable:

if (is_numeric($_SESSION['user']) && $_SESSION['user'] > 0) {
    do_something_super_secret();
} else {
    redirect_to_login();
}

In other words, PHP only creates/restores the $_SESSION array for you, based on the session cookie. It is completely up to you to build something (such as authentication) on top of this.

Piskvor left the building
  • 87,797
  • 43
  • 170
  • 220
  • I understand this case when we are using session variables. But I am trying to understand the same thing with the cookie that gets sent and what role does it play in the login as we are not cross checking it explicitly anywhere. Are we ? – qre0ct May 07 '14 at 16:35
  • The cookie only serves as an identifier for the session, *nothing more*: "Your session ID is 1234567890," everything else is stored server-side in the session. The session ID is not validated automatically (you'd need to do this yourself), PHP considers any session ID valid. – Piskvor left the building May 09 '14 at 08:02
0

Huh? I don't see what is the real problem here.

When you create a session, it is saved on the server within a folder. (Configurable)

The cookie is important (There is no other way to check which session belongs to the visitor), so this is the only way to save things.

Mostly you don't have to care about things like this. (session)

When the user press the LOG IN button (post form), then this happens on the server (PHP):

1 The data of the form is in the $_POST global (associative array, INPUT Name => INPUT Value

2 You check that if the value is valid or not, if valid, compare the values to the database's values

3a. Successful login, you set a session about the login data. (ex.: $_SESSION["login"] = array("id" => $id, "username" => $un, "password" => $pw); ) Don't forget to encrypt the password (never save plain password into db)

3b. The login failed, show an error to the visitor.

4 The user is logged in, server compares the data in the session against the db values

4a. Values are valid continue

4b. Values aren't equal to the db values, log out the user ( delete the session: unset($_SESSION["login"]) )

5 The visitor visits the 'restricedPage.php' if the session data IS VALID and EXISTS then continue, otherwise redirect to 404 or to a visitor page

Edit:

A cookie is set by session_start(), so you the server can find the session assigned to the visitor (sessionid).

Every configuration for the cookie can be found in the php's configuration.

The cookies value contains a single 'character sequence' (?) which is the visitors session's id. (If you know other visitor's session's id you can change your cookie's value to the other visitor's one, so never make the ID public in any form.)

You can get the cookie's params by the 'session_get_cookie_params()'.

Returns an array with the current session cookie information, the array contains the following items:

"lifetime" - The lifetime of the cookie in seconds. "path" - The path where information is stored. "domain" - The domain of the cookie. "secure" - The cookie should only be sent over secure connections. "httponly" - The cookie can only be accessed through the HTTP protocol.

The quote is from the PHP's documentation: http://sg2.php.net/manual/en/function.session-get-cookie-params.php

Dávid Szabó
  • 2,119
  • 1
  • 12
  • 24
  • i was not referring to setting a cookie explicitly. I was talking about the cookie that is auto set by session_start(). Can you provide inputs on that ? That's the whole point of the confusion. – qre0ct May 07 '14 at 16:15