How to Use PHP Sessions

How to Use PHP Sessions thumbnail
Using PHP is moderately difficult.

The PHP hypertext preprocessor (PHP) computer language can store user variables across several web pages in session variables. This ability comes in handy for websites that require registration and membership, allowing users to remain logged in even when they leave the website. Session variables also are a convenient way to keep user information on hand across several web pages, allowing users to visit other users' profile pages, comment and rate without re-entering membership information.

Things You'll Need

  • Web server with PHP 5 installed
  • PHP integrated development environment (IDE) or text editor
Show More

Instructions

    • 1

      Include the following script in each PHP file that you want to process session variables: session_start();

    • 2

      Create a session variable using the following script in order to begin inserting variables into a user session: $_SESSION['x'];

      That script declares a session variable under the name "x." Replace "x" with a name that describes the variable you want it to store.

    • 3

      Store a local variable in the session variable using the script $_SESSION['x'] = y;

      Replace "y" in the script with the name of a local variable you hope to store inside the session variable. To store a user's profile identification into a session variable, for example, you could write: $_SESSION['user_id'] = 11;.

    • 4

      Retrieve and process session variables. Session variables can be used like normal, local PHP variables. To reference them, use this script in which "x" stands for the session variable's predefined name: $_SESSION['x'];

Tips & Warnings

  • In order to retrieve a session variable, a PHP file must call the session_start() function before attempting to reference the session variable stored from another page.

Related Searches:

References

Resources

  • Photo Credit Jupiterimages/Photos.com/Getty Images

Comments

You May Also Like

Related Ads

Featured