Store a Post'ed Variable Into a Session

Hello.

I would consider myself brand new to PHP and programming in general. So please be explicit in your posts if you can in your explanations. I do well with logic and reasoning.

Ok, on to my goal, problem, and question.

I am currently attempting to code a website where visitors are able to post their own media, news bits, as well as browse those posted by others. These pages are protected by a relatively simple login script that I had simply looked over, typed into Notepad++ myself, and modified to work with my own environment.

I wish for every page that a user is logged into to display their own username near the top of the webpage. The problem is, I don’t know exactly how to implement such a feature using the existing login script that I have.

I have read around that you can use sessions or cookies to store variables for later retrieval in PHP. (The only difference between the two is when the data expires). I’d rather use sessions if possible.

Here is the login code that I am using on the site:
[php]

<?php //allow sessions to be passed so we can see if the user is logged in session_start(); ob_start(); //make attempt to submit post data into session data //connect to the database so we can check, edit, or insert data to our users table $con = mysql_connect('hostname', 'user', 'password') or die(mysql_error()); $db = mysql_select_db('database', $con) or die(mysql_error()); //include out functions file giving us access to the protect() function made earlier include "./functions.php"; ?> Login To Your Account <?php //If the user has submitted the form if($_POST['submit']){ //protect the posted value then store them to variables $username = protect($_POST['username']); $password = protect($_POST['password']); //Check if the username or password boxes were not filled in if(!$username || !$password){ //if not display an error message echo "You need to fill in a Username AND a Password to login!"; }else{ //if the were continue checking //select all rows from the table where the username matches the one entered by the user $res = mysql_query("SELECT * FROM `usertable` WHERE `username` = '".$username."'"); $num = mysql_num_rows($res); //check if there was not a match if($num == 0){ //if not display an error message echo "The user " . $username . " is not in our records. Check your spelling."; }else{ //if there was a match continue checking //select all rows where the username and password match the ones submitted by the user $res = mysql_query("SELECT * FROM `usertable` WHERE `username` = '".$username."' AND `password` = '".$password."'"); $num = mysql_num_rows($res); //check if there was not a match if($num == 0){ //if not display error message echo "". $password ." is not the correct credentials for " . $username . "."; }else{ //if there was continue checking //split all fields fom the correct row into an associative array $row = mysql_fetch_assoc($res); //check to see if the user has not activated their account yet if($row['active'] != 1){ //if not display error message echo "You must first ACTIVATE your account to use it."; }else{ //if they have log them in
						//set the login session storing their id - we use this to see if they are logged in or not for users Online.
						$_SESSION['uid'] = $row['id'];
						//show message
						echo "<center>You have successfully logged in. Continue.</center>";
						//update the online field to 50 seconds into the future
						$time = date('U')+50;
						mysql_query("UPDATE `usertable` SET `online` = '".$time."' WHERE `id` = '".$_SESSION['uid']."'");
						//redirect them to the home page
						header("Location:homepage.php");
					}
				}
			}
		}
	}
	?>
	<form action="login.php" method="post">
		<div id="border">
			<table cellpadding="2" cellspacing="0" border="0">
				<tr>
					<td>Username:</td>
					<td><input type="text" name="username" /></td>
				</tr>
				<tr>
					<td>Password:</td>
					<td><input type="password" name="password" /></td>
				</tr>
				<tr>
					<td colspan="2" align="center"><input type="submit" name="submit" value="Login" /></td>
				</tr>
				<tr>
					<td align="center" colspan="2"><a href="register.php">Registration</a> | <a href="forgot.php">Forgot Password?</a></td>
				</tr>
				<tr>
					<td align="center" colspan="2"><a href="newactive.php">No Activation Email?</a> | <a href="dd-home.php">Back to Home</a></td>
				</tr>
			</table>
		</div>
	</form>
</body>
<? ob_end_flush(); ?> [/php]

The code below is what’s on homepage.php . Note that this is not the complete code; only the php parts are included.

[php]

<?php //Start Session to retrieve session variables (Doesn't work, Coding issue?) session_start() ?>

… [ To Next Section of PHP ] …

<?php //Check to see if a session does exist if(strcmp($_SESSION['uid'],"") == 1) { //If the session does, display the username of the user logged in. echo "The $username var does not work!
View Users | Logout"; } else { //If the session does NOT, display notification and LOGIN link. echo "You are not logged in!
Login Here | Registration"; } ?>

[/php]

There has to be some way of capturing the $username variable and storing it into the same session along with the login check when the user logs in and is redirected to homepage.php. That way I can recall it using $_SESSION[‘username’] = $username.

Okay, I quickly looked over your code. I am not sure if you understand session variables. I will give you some general info on them and hopefully that will help you.

First, are you using the PHP-OBJECT for any special reason? Do you know what that is for?
I mean the --> ob_start(); <-- and object flush at the end? This is used to take a “snapshot” of the
page you are creating and save it into a variable for future use. It has nothing to do with session’s…
Just want to make sure you were not thinking you needed that for session usages.

So, session usage is extremely easy to use. Only three small things to learn.

  1. EVERY page that uses session variables MUST start the session. ( session_start(); )
    (If it is not on a page $_SESSION[’’] will not work! AND, it should be first PHP code
    and preferably above the of the HTML page.)

  2. Use this code anywhere on the page whenever you need to set a session variable:
    $_SESSION[‘variable-name’] = value; (The variable names are case-sensitive. $xyz is NOT $xYz !
    and can be any type of PHP variable. Including arrays, integers, floats, anything PHP handles!)

  3. Retrieve any session variable like this: $newvariable = $_SESSION[‘passedvariable’];
    (The new variable is assigned whatever was stored into the session variable from the previous page.)

And, if you remember those three items, that is all you need to know. It works well, is much more secure than any cookie will ever be. Here are a few notes on the details:

Session variables have a scope of the session.
When the website is left, the session variables are gone.
A session is basically a connection from a computer to the webpage. (using IP and browser connection)
The current session has several internal values that are not general used by programmers.
(Such as the actual session number which is used sometimes for security routing.)
Session variables are actually an array of variables, hence the [] used when accessing them.

So, that covers all there is to learn for 99% of session variable programs. Now a few notes on how your type of project usually works…

The first page of the site is a log in page. The user enters data such as user id and password.
This data is verified (validated) using previously stored records in a database. Next, the session
variables are set using more data from the database. I use the UserID as I like it best for this use.
This log in page starts off before the HTML/Javascript/CSS code is active with a PHP script that just
starts the session. The server sees that a session is starting and memorizes the IP and other items
that it needs to keep the session open.
Next, after the user is validated and okayed, they are pass to another page. This page starts off
again with session_start(); which again tells the server to start a session, but, it knows it is the
same session since it came from the same webpage and IP address. The first part of the actual
display, uses a small PHP IF clause to check to see if $_SESSION[‘UserID’] is set or not. If not, it
echos a statement like echo “Welcome Guest!”; …
But, if it is set, echo "Welcome " . $_SESSION[‘UserID’]; So they see one or the other depending
on how the session variable is set.

I use session variable’s for lots of items. Such as one page someone is on so the next page has a
backward arrow to send them back to where they were, not just back to the home page. Or, the last
date/time they logged in pulled from the database when the logged in. Or, something like the favorite
color so the background of every page is based on the color they stored in the database.
Tons of uses and all LIVE while the user stays on the site. They close the website, all session info is
gone. So, secure, nobody can steal the data. It doesn’t exist after they log out. The only catch is if
a user changes something that you set into a session variable, it must also be written to the database
for future use.

Well, there you go, just about everything I know about session variables. Hope this helps!

Let us know if you have trouble getting them in place… Good luck!

Thank You Ernie, your post helped clarify a lot about the nature of session variables. To answer some questions you asked me:

  1. First, are you using the PHP-OBJECT for any special reason? Do you know what that is for?

I mean the --> ob_start(); <-- and object flush at the end?

Nope. At both questions. I was not the author of this code. The only adaptations I’ve made is to the actual messages echo’d by the script. This was more or less an attempt to learn by watching it in action more than designing and writing it.

So by your explanation of what the ob_start() function is, it is unnecessary for it to have any place in the script. It would seem to be fitting more in a debugging situation.

  1. The first page of the site is a log in page. The user enters data such as user id and password.

This data is verified (validated) using previously stored records in a database. Next, the session
variables are set using more data from the database. I use the UserID as I like it best for this use.
This log in page starts off before the HTML/Javascript/CSS code is active with a PHP script that just
starts the session. The server sees that a session is starting and memorizes the IP and other items
that it needs to keep the session open.
Next, after the user is validated and okayed, they are pass to another page. This page starts off
again with session_start(); which again tells the server to start a session, but, it knows it is the
same session since it came from the same webpage and IP address. The first part of the actual
display, uses a small PHP IF clause to check to see if $_SESSION[‘UserID’] is set or not. If not, it
echos a statement like echo “Welcome Guest!”; …
But, if it is set, echo "Welcome " . $_SESSION[‘UserID’]; So they see one or the other depending
on how the session variable is set.

While this is definitely not a question, this outline of the basic process helps me refine what I was attempting to ask originally.

[b]Next, the session variables are set using more data from the database.[/b]
How to correctly implement such a feature. Hopefully I can pin this down.

Using what I have learned so far from your post and from what I could understand from the PHP manual, the thing to do would be to store the variables such as $username into the $_SESSION array, so that they can be recalled on another page instead of having to pass these through an URL in an insecure manner (GET Request). This would be done by doing something such as:
[php]
$username = $_SESSION[‘username’]
[/php]

On those other pages, I must ask PHP to start a session using the session_start() function, and PHP will recognize if there is already an existing session associated with that client using the IP address of that client, and therefore allow access to the $_SESSION array variables if any exist inside already if that is indeed the case.

If this assumption is correct, it would look like this in PHP :
[php]
/* -= Example Login Script =- */

<?php //This function starts a session if none exists, and resumes a session if one does exist session_start() //In a production situation, a database would provide these variables using various functions native to that database. $username = Iamuser $password = Icomefromdb if ($username = Iamuser And $password = Icomefromdb) { //Log the user in, credentials match. $loggedin = 1 } else { //Don't log the user in, credentials do not match. Let user know. echo "You do not have the correct username or password to access this page." } //The script ends its tasks ?>

[/php]

…and on other pages.

[php]
/* -= Example Check Authentication Script =- */

<?php //This function starts a session if none exists, and resumes a session if one does exist session_start() //This code will check if the user is logged in using a variable from the $_SESSION array stored earlier. if ($loggedin == 1) { //Tell the user they are logged in echo "Welcome $username; You are logged in!" } else { //Tell the user they are not logged in echo "You are not logged in!" } //The script ends its tasks ?>

[/php]

…probably should have reviewed that PHP code more carefully, I’m missing a ton of closing marks ( ; )and have tried to set instead of check for equality in the login script ( = ) instead of ( == ).

Yes, MrMaverick, That would be the “general” lay out of how to do your log-in system. Normally for the database section, you would have created a database. Created a few tables, one being for your log-in’s user-id and password. Usually, this would be called something like “Users” or “Admin” or “RegisteredUsers” or some other name that makes sense to you. Then, in that table, you would have all of the registered users data. This could include items such as User-ID, Password, Name, Address, Email, User-Status, Date-Registered and any other data you might need. I use the UserStatus to indicate if the user has sent a registration request, was okay’d as a member, paid their dues, whatever might be important to your use.
Note this is just an idea for you to think about, in general terms.

Glad I could help, ask any other questions you might have… Good luck with your project…

Thanks Ernie. I marked it as solved. I shall come back here for more help, I guarantee it.

This post is specifically to correct my mistakes from the previous post so that users whom land on this thread may be able to understand better about this topic.

  1. First off, if you want to store a variable in a $_SESSION array, you must set the new variable on the left side:
    [php]
    $username = $_SESSION[‘username’]
    [/php]
    The above code is incorrect if I want to set a session variable; according to PHP, I am trying to set variable $username from a $_SESSION array variable called username. But we want the opposite. So:
    [php]
    $_SESSION[‘username’] = $username
    [/php]

Syntax is important.

Also, ensure that each line with a function ends in a semicolon ( ; ). This tells PHP that there is no more code on that line, and it will go to the next line to parse the script.

These are the corrected example scripts below:
[php]

/* -= Example Login Script =- */

<?php //This function starts a session if none exists, and resumes a session if one does exist session_start(); //In a production situation, a database would provide these variables using various functions native to that database. $username = Iamuser $password = Icomefromdb if ($username = Iamuser And $password = Icomefromdb) { //Log the user in, credentials match. Note that if you wish to take this variable across pages, you have to pass it through an url, set some sort of cookie, or use a session; all listed from least secure to most secure. /* This will not work, the variable only exists on this page */ $loggedin = 1 /* This will work; the variable is accessible through a session (other pages have to include the session_start() function). */ $_SESSION['loggedin'] = 1 } else { //Don't log the user in, credentials do not match. Let user know. echo "You do not have the correct username or password to access this page."; } //The script ends its tasks ?>

[/php]

Other Corrected Example Script:

[php]
/* -= Example Check Authentication Script =- */

<?php //This function starts a session if none exists, and resumes a session if one does exist session_start() //This code will check if the user is logged in using a variable from the $_SESSION array stored earlier. if ($_SESSION['loggedin'] == 1) { //Tell the user they are logged in echo "Welcome $username; You are logged in!"; } else { //Tell the user they are not logged in echo "You are not logged in!"; } //The script ends its tasks ?>[/php]
Sponsor our Newsletter | Privacy Policy | Terms of Service