PHP Sessions

Status
Not open for further replies.

Axehack

In Runtime
Messages
110
Location
http:\\www
Background:
Hi all, I am trying to do a bit of coding for a website I am writing, Although beyond the scope of what i need to do, if i could use sessions, it would be advantagous.

Problem: I am using on a logon.html page a simple:
<?
session_start();
?>

Then on the logon.php

<?
$_SESSION['forename'] = $forename;
?>

Then at a later point, i want to display the forename (Which doesnt work) using:
<?
print
$_SESSION['forename'
];
?>


I have also tried
<?
echo "Forename: ",
$_SESSION['forename'
];
?>

If you can tell me why it doesnt work and correct it for me... i promise +rep! :D

[edit] This isn't exactly what im doing, it is heavily simplified, but if i can get this little bit of code to work, I can solve the rest. Cheers
 
You need to put session_start() at the beginning of every page. Not just the first.

Also, unless you specifically set your server to parse HTML files as PHP, they won't do anything.
 
Thanks for a quick reply, I am working on this as we speak and have discovered the session_start() at the begining of each page bit....
I have it down to just 2 pages for now

Login.php
< ?
session_start();
$_SESSION['forename'] = $forename;
$_SESSION['surname'] = $surname;
?>

Loggedin.html
< ?
session_start();
echo "forenames=". $_SESSION['forename'];
echo "surname=". $_SESSION['surname'];
?>

I am doing this on the uni server so no modifications on that end will be possible... Should I just change the loggedin.html to a .PHP ?
Im guessing what your saying is that the session code must be in a .php file to work?
or are you saying ALL php coding must be in a .php to work unless its configured on the server?

I believe we use .html files with .php embedded which work, so the server is already configured?
 
No, im afraid that would not be sufficient. We have a set plan we must stick to on multiple pages.
Does anybody know why it is not working?
 
Well first of all it's hard to help you with code when you're simplifying things!
Generally Login forms need something to compare to. I.E. You need to be matching information to a database.
Without a database information won't be able to be retained.

I'll try to make some suggestions, hopefully it will help you solve what it is you are trying to accomplish.

When I work with sessions I like to split it up into a few different documents

header.php
--> Here is where you open all your html document, link to all your external css files and any navigation

footer.php

--> Footer.php contains the address line that will be shown at the bottom of every page and a single line of php code after the html tags are closed.
<?php
ob_end_flush();
?>

initalize.php
ob_start();
if (!isset($_SESSION))
{
session_start();
}

---> Initalize.php is an extremely important piece, this document will look to see on every page if a session has been initiated, If it has it will call up that session where user information is stored, or if the session tests negative it will open one. This file is called in after the header in the body content portion of every page

After this we can start getting into the meat programming the GUI

welcome.php
---> A very basic page as far as content goes, all it really needs to have is WELCOME in big letters, if you are not already familiar,
here we will have our first encounter with a new term. "include_once".
include_once("templates/initalize.php");
include_once("templates/header.php");
?>
<h4> WELCOME </h4>
<p>Please register to order any books from out library.</p>
<br />
<?php
include_once("templates/footer.php");
?>

include_once calls other pages into the php document. By calling initalize.php we can automaticly check if a session has been started without hardcoding this php script into every single page. It is the same concept for header.php but instead php calls to the document that contains the nav menu list and the link to the external stylesheet.

So now we need to build the register page

register.php
--> Here we create a form using the same template as the welcome page. Where welcome is printed on the previous page we will build a form that contains text input fields for: First Name, Last Name, Credit Card, Street, City and Postal code. You can make your forms sticky (they remember information if user makes a mistake and the page refreshes) the code for this follows the basic html form convention with one exception. In the Value field is a small portion of php which will check to see if any information has been entered into the session and will echo that information back.
<input type="text" name="first_name"
value="<?php if (isset($_SESSION['first_name'])) echo $_SESSION['first_name'];?>">
</input>


So the form is done! SWEET! now let's store all that information and run some Validations to make sure there's no funky user input hiding

create_account.php
---> The registration form will be sent to the create_account.php document to be processed, this file will import all of the text entries from the previous form and will store them into your session.
After the entries have been stored into the session the script will check to see if more than one character has been enetered into all value fields. If one is missing you will be returned to the register.php file untill this condition is satisfied. Once all conditions are met and the form is re-submited the header will relocate you to the bookstore.php

you'll notice I use a strip_tags function on all requests. If a user has tries to enter html or anything other type of code, it will be deleted from the user input.
include_once("templates/initalize.php");

$first_name = trim(strip_tags($_REQUEST['first_name']));
$_SESSION['first_name'] = $first_name;
$last_name = trim(strip_tags($_REQUEST['last_name']));
$_SESSION['last_name'] = $last_name;
$credit_card = trim(strip_tags($_REQUEST['credit_card_number']));
$_SESSION['credit_card_number'] = $credit_card;
$street = trim(strip_tags($_REQUEST['street']));
$_SESSION['street'] = $street;
$city = trim(strip_tags($_REQUEST['city']));
$_SESSION['city'] = $city;
$postal = trim(strip_tags($_REQUEST['postal']));
$_SESSION['postal'] = $postal;

if (strlen($first_name) > 1 && strlen($last_name) > 1 && is_numeric($credit_card))
{
if (strlen($street) > 1 && strlen($city) > 1 && strlen($postal) > 1)
{
header('Location: bookstore.php');
}
else
{
header('Location: register.php');
}
}
else
{
header('Location: register.php');
}
?>

header('Location: '); is the code used for re-directing to another page, when you would like to process a form and conditions are not met you can tell php to return the browser to the registry or to continue onto your store.


You only get one more piece. :lol:

bookstore.php
---> Contains a few interesting things, immediately after we call our include_once commands an if loop is executed to see that if the "first_name" session has not been initialized on our registration form, the website will automaticly redirect you back to the registry page, this way you can not skip the registration and go directly to shopping.

include_once("templates/initalize.php");
include_once("templates/header.php");

if (!isset($_SESSION['first_name']) && !isset($_SESSION['last_name']) && !isset($_SESSION['address']))
{
header('Location: register.php');
}
?>

<form action="process_orders.php" method="post">
<fieldset><legend>Enter which title you would like to order.</legend>
<br />
<label>Author
<input type="text" name="author"
value="<?php if (isset($_SESSION['author'])) echo $_SESSION['author'];?>">
</input>
</label><br />

<label>Title
<input type="text" name="title"
value="<?php if (isset($_SESSION['title'])) echo $_SESSION['title'];?>">
</input>
</label><br />

<input type="submit" name="submit" value="Buy" />
</fieldset>
<fieldset><legend>Are you done shopping?</legend>
<input type="submit" name="done" value="Done">
</fieldset>
</form>
<?php
include_once("templates/footer.php");
?>

My app contained two buttons, a BUY button if you would like to add the book to your cart then continue shopping and a DONE button to continue on to the shopping cart. You will see that corrisponding names have been assigned to both buttons above.

When you are done everything sessions are needed for --> Destroy! Destroy!


session_destroy(); will delete all information entered into the session when a user has completed using this website and leaves the forms empty for the next person.

In your senario this would be called on the bottom of your 'log out' page.

<?php
session_destroy();
include_once("templates/footer.php");
?>

TERMS


include_once :includes and evaluates the specified file during the execution of the script. As the name suggests, it will be included just once.

header : The header() function sends a HTTP header to a client. It is important to notice that header() must be called before any actual output is sent
In PHP 4 and later, you can use output buffering to solve this problem.

sessions : preserves certain data on the server side. This enables you to build more customized applications and increase the appeal of your web site. All information is in the Session reference section.

session_start(); : starts a new session for the user whose using your web application


session_destroy(); : deletes all information fromm the session when a user has completed what they're doing.


ob_start(); : This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.


ob_end_flush(); : This function will send the contents of the topmost output buffer (if any) and turn this output buffer off. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_flush() as the buffer contents are discarded after ob_end_flush() is called.

IN CLOSING
I hope that helped, I'm sure anything past this you can figure out on your own.
This app I built will retain sessions as long as the page/browser is left open.
Us PHP nerds tend to be pretty reliable when it comes to problem solving :)
 
I had almost given up hope on a response to this question! Iv not had time to implement this yet, but from what iv read, its almost exactly what im looking for.... Sadly it seems sessions are not as simple as I first thought, but if i can get this working im sure ill get some +Rep! :)

Thanks a heap for your time! This is far better explained than I expected and an excelent walk through!!! Big Thumbs up! :D
 
You are very welcome :) You're lucky that I had actually prepared this tutorial for my friends last year when we were all building bookstore apps so everything is written in a language most beginners would understand. It was just a matter of changing the language a little bit to fit the situation and applying some nice typography.

And definately! Get it working and impress your PHP buddies. :lol:
Feel free to ask PHP stuff anytime.
 
Hey Draconian, I know this is an old post, but i just thought I'd let you know... I finally got round to using Session cookies last week and implemented your suggestions and all is running sweet as a nut! Perfect! Thanks again! :)
 
Status
Not open for further replies.
Back
Top Bottom