PHP Sessions
Syntax
A session in PHP is started using the session_start()
function. The syntax for starting a session is:
session_start();
Example
Here is an example of setting a session variable and echoing it out on a page:
<?php
session_start();
// Set session variable
$_SESSION['username'] = 'john';
// Echo out session variable
echo "Welcome, ".$_SESSION['username']."!";
?>
Output
When running the above code, you should see "Welcome, john!" displayed on the page.
Explanation
A session in PHP is used to store information across multiple pages on a website. When a session is started, a unique session ID is created for the user. This ID is used to track the user's activity on the website and allow for data to be stored and retrieved across multiple pages.
In the above example, the session variable 'username' is set to 'john' using the $_SESSION superglobal array. The value of the session variable is then echoed out on the page.
Use
Sessions are commonly used in PHP to keep track of user authentication, shopping cart contents, and other user-specific data across multiple pages.
Important Points
- Sessions in PHP are started using the
session_start()
function. - Session variables are stored in the $_SESSION superglobal array.
- Session variables can be used to store and retrieve data across multiple pages on a website.
Summary
PHP sessions are a powerful tool for storing and retrieving user-specific data across multiple pages on a website. They can be used for a variety of purposes, including user authentication and shopping cart functionality. The session_start()
function is used to start a session, and session variables are stored in the $_SESSION superglobal array.