Hi, I am new at php so please I beg of you to go easy on me., I have looked on the site and read many tutorials but I am trying to understand the following:

When I call session_start() at the beginning of a page a file gets saved to the temporary location on the server, I can then store user data in the session and call them on all pages where I use session_start().

What I don’t understand is: how does session_start() know which user im referring to? if I have many users accessing the same page (in my instance the members area) then for each user a different session is saved, how do I differentiate betweens users session.
I noticed that each session has a name like (sess_o84gfg3cmtpn0n7seshjp7egj5) does the name of the session file have anything to do with it?

What I have in mind is that I want to be able to identify the users session and store this identifier in my database, on each request I want to find that session file, create a new session and transfer all the data from the current session to the new session and kill the old session, at the same time updating the identifier for the new session in the database. I also want to encrypt the data that is stored in the session file.

I am also curious to the following, from what I understand, a session is a method of storing temporary data that can be accesses globally, it also gets destroyed when not used for a while. Ive also learnt that there is some loop holes is sessions and my knowledge is insufficient to cover theses security holes. Why cant I then just store the data in my database? If I can use my database opposed to sessions, then how do I identify the user without using thier ip address, considering that ip addresses could change etc?

Does anyone know of a site like this that has a chat room where i could chat to someone live, im hitting alot of stumbling blocks!!

Please help me understand the above and guide me in the right direction
Regards

Recommended Answers

All 13 Replies

sessions can be useful for a variety of reasons. One is like you said to store data between pages. I'll give you a little example where your username is stored and can then be displayed at the top of the page.

Lets say you have variable which stors the users username.
$usernamevar = "Jimmyo88"

You can then store this variable and place it within a session which will be stored for later use in different places.

For a session you need to give it a name and the data you want it to store. There are other parameters but this will probably be all you need for the moment.

$_SESSION['username'] = $usernamevar;

Look at the above code it declared a session using $_session
then the part is the name of the session and then the end bit is the variable you want to give it.

So at this point the session username is assigned with the value of $usernamevar.

Lets say you now navigate to a new page and want to use the session you have just stored.

echo "Welcome, ".$_SESSION."

In this case this would echo "Welcome Jimmyo88". This is because we have stored jimmyo88 under the session name of username.

Does this make sense to you?

P.S remember, the session would be set on the login page.

if (username and password = correct)
{
$_SESSION['username'] = $usernamevar;
login;
}

hope this helps, let me know if your still stuck.

PPS. just think of session_start() as a way of telling the computer, "hey im gonna be using sessions on this page". The way everybody uses sessions is by using a variable like we did for username.

Thank you, your explanation is clear.
if you have a bit more patients... lets say
Both jimmy and alex logged in at the same time,
how did the server know that the session holding the variable data $usernamevar
is for jimmy and not for alex, in the same way, if jimmy logs out we will use session_destroy, how does the server know which session to destroy?

it doesn't make any difference. Let's say both Jimmy and Alex are using your website.
They'll both be accessing their own copies of the code to a certain extent. So alex's session will have the $username variabe set to alex and Jimmy will have his set to Jimmy.

If e.g. your thinking..."but how would the session variable know which user to choose."
1.You have your login page with a form which says username and password.
2.The user enters his or her details.
3. When the user clicks submit, his username is put in a global variable using $username = $_POST
4.then you can use the $username variable and put it in a session.

Let me know how you get on

As you said earlier:

1. You have your login page with a form which says username and password.
2. The user enters his or her details.
3. When the user clicks submit, his username is put in a global variable using $username = $_POST
4. then you can use the $username variable and put it in a session.

After this I save the variable into a session with $_SESSION[username] = $username

at this point a have successfully saved the users username into the session.

keep in mind that the sessions are stored on the server, the client does not know that the username is coming from a variable stored in the session and the server does not know that the request is coming from jimmy because we havnt told the server, all that we did was we used session_start and echoed the global variable $_session[username]

i could have 100 users each with a different session containing $_session[username].

How does the server know that the browser is sending a request from jimmy or alex so that the server can in turn use the correct session file?

if i can figure this out i can attempt to manipulate whatever it is that the browser is using to identify to the server which session file has been created for that particular user.

well on your logon page you would have the user enter his or her password. Using the details from this page, these would be compared to the details in the database. If the match is successful, then the code to set the session is run.

Remember the variable that the session uses would be set by the username field in the logon page.

session_start(); //nothing else here, just telling the compiler, "i'm going to use sessions"
$username = $_POST['username'];     //getting the username from the form and placing it in the variable $username
$password = $_POST['password'];     //getting the password from the form and placing it in the variable $password
if ($username && $password) 
{
	
$connect = mysql_connect("localhost","root","root") or die("couldn't connect"); //connect to databse
mysql_select_db("login") or die ("couldn't find db"); //connect to databse
$query = mysql_query("SELECT * FROM users WHERE username = '$username'"); //query databse, select all users where the username is equal to the inputted username

$numrows = mysql_num_rows($query); //get the number of rows from db

if ($numrows!=0) //if the number of rows does not equal 0
{
	//code to login
	while($row = mysql_fetch_assoc($query))
	{
	$dbusername = $row['username']; //get the database username
	$dbpassword = $row['password']; //get the password from the db
	$dbtype = $row['type'];
	}
	
	//check to see they match
	if ($username == $dbusername&&md5($password) == $dbpassword) //if the inputted username and password is equal to the db username and password.
	{
	 echo "You have logged in!
         $_SESSION['username'] = $username; //set the session ONLY IF THE USERNAME AND PASSWORD MATCHES TO THAT IN THE DATABASE.
        }
else    {
        echo "Incorrect username or password";
        }

Take a look at the above code. First the fields from the database are gathered. Then a check to see that there is a match for both a username and password. Once this has been done, a message saying "you have logged in" is echo's and the session is set to whatever username has been entered. If the user enters the details wrong, a message saying incorrect username or password is echo'd and the session is not sent.

Because you are setting the session after the user has filled out the form, you know which user is setting a session thanks to $username variable is set.

Remember, the session is not a file on the server which dishes out details it already has. The session is dependant upon what is given to it. In our example we're using a username from a form after it has been checked with its password.

Try and let me know exactly what you wan't to use sessions for.

Agree and understand 100% with the above.

theres still something in between that's missing - between the server and the client,there must be something that tells the server which session to read from.

username was added by the code to the session AFTER the session was created, no where do we identify the actual session, all that we identify is data stored in some session, similarly when we use the function session_destroy,
we are destroying a session without identifying which session amongst 100's of sessions.
We not saying: destroy the session WHERE($username == $_SESSION[username]).

a simple function: session_start() creates a session file for jimmy and alex and the guy in china and germany INDIVIDUALLY. it would make more sense if the function was like session_start(alex),session_start(jimmy) and session_destroy(alex) etc.

There must be an identifier for the session file that stores the session data,
otherwise the server would not know where the request is coming from.

i want to store the name of the session file in the database and on each request create a new session for that user,
override the new session name in the DB,
transfer the data from the old session data to the new session,
and destroy the old session so that even if someone got hold of the users session it wouldve been destroyed.

I also want to encrypt the session data so even if the above fails the data would be encrypted and even if the hacker decrypted the session data, it would be a dead session. the encryption would be random and the solution stored in the database so even if the dead session was decrypted, the same decryption would not work on another session file... but first thing first,
back to my session identifier cry for help

your still missing the point of the session_start. Session start literally tells the computer that you are going to be using sessions. It doesn't assign anything to anyone or do anything special other than letting the computer know that you may be using sessions.


"a simple function: session_start() creates a session file for jimmy and alex and the guy in china and germany INDIVIDUALLY. it would make more sense if the function was like session_start(alex),session_start(jimmy) and session_destroy(alex) etc."

This is not right, remember session_start only tells the computer that you are using sessions.

The server knows which person is using sessions by which user has logged in.
Thats why you have $_SESSION = $usernamevar;
Doesn't matter who logs in because they'll always be assigned to the username variable.

If you were to have $_SESSION = Alex; and so on then how would the compiler know which user to use. Thats why the username is always assigned to a variable.

"There must be an identifier for the session file that stores the session data,
otherwise the server would not know where the request is coming from."

the identifier is the part in the square brackets, i.e, username. The computer knows where the request is coming from because the session is only set after the user has logged in. and by using the details which the user has entered on the login script, these can then be assigned to the session identifier.

"
i want to store the name of the session file in the database and on each request create a new session for that user,
override the new session name in the DB,
transfer the data from the old session data to the new session,
and destroy the old session so that even if someone got hold of the users session it wouldve been destroyed"

I know what you want to do but why would you want to store the name of the session in the database? Most things that use sessions, i.e. usernames are already stored in the database. What are your actual aims? I know what you want to do, i just don't know why? Try and give me a practical example if you can?
I'm not 100% sure that its sessions you actually want or need?

P.S about the encryption, i'm not entirely sure about what you need to encrypt. If you look at the example code I gave above, on the login part, you can see where the passwords are encrypted using MD5 and if you were to look in the datatbase, the passwords would be in md5 format aswell. I'm not too hot on encryption mind so can't help you too much there.

@designalex Sessions are identified by a cookie that is sent to the browser when a session is first initialized. The session_id contains a key that points to the right set of session data. If a user has disabled cookies, this becomes problematic but a session id can also be passed in the querystring of the url.

if the cookies are disabled, does the browser automatically send it in the url and doesnt this become a security risk?

other than cookies and the url, is there any other way of sending a key or session id?
could a hidden input not work?

following a few threads and tutorials etc i picked up on something session_regenerate (im probably saying it wrong), either way, does that function help regarding session hijacking. im working on a site that needs to be secure , user accounts etc and im just doing my homework before i dive in, thanks in advance

i can't answer that for you sorry Alex. Maybe someone more talented will come to your aid?

Member Avatar for diafol

If cookies are disabled, sessions (cookie based) will not work. You can however, save session data to DB. That is a whole new topic though. You need to session_set_save_handler(). There are a number of tutorials online as to how to save session data to DB as opposed to writing data to a cookie. If you're new to php, take a deep breath...

http://www.php.net/manual/en/function.session-set-save-handler.php

i am new to php, although i have used sessions before, it was only on straight forward sites.

please correct where i am wrong,
from what i am understanding, sessions are a way of identifying a user.
The id can either come from a cookie or a URL so even if i use session_set_save_handler() and cookies are disabled the session id will be sent via the URL,
considering session fixation, sending the session id via the URL is not an option

Now my questions are as follows

question 1:
If the clients cookies are disabled will the browser automatically send the session id via the URL, if this is true then is there a way that i can detect it and maybe stop the request with a message like: cookies are required for this site to function!

Question 2:
seeing that it is only the session id that is stored on the clients machine in a cookie, cant i use a hidden field to store the session id

Question 3:
on certain sites, if you log in to a site with any browser and open a new tab or window useing the same brower and reviset the same website that you have logged in to, then on the new tab or window you will automatically be logged in.
on other sites even if you open another tab or window within the same browser, you will have to log in again. i find the later to be safer as we dont assume that the new tab or window is the same user, how is this achieved?

I know im stretching this thread a bit, but im just not wrapping my head around it yet!

Member Avatar for diafol

Q1 - You can check the setcookie() to see if cookies are enabled.
Q2 - hidden fields require forms to propagate them - yuk!
Q3 - exitpopups can form the basis of this automated logout. Have js do an 'onunload'. It's not something I've used though.

I suppose you could have a http_referer (not infallible) check to see if the last page (if it exists) was on the same domain - if not - force a login / session destroy.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.