Sessions In Php With Examples

Sessions In Php With Examples

A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.

Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.

So; Session variables hold information about one single user, and are available to all pages in one application.

Create a PHP Session

A session is started with the session_start() function.

Session variables are set with the PHP global variable: $_SESSION.

Put this code in a test.php file and load this file many times to see the result –

It will produce the following result –

Note: The session_start() function must be the very first thing in your document. Before any HTML tags.

Cookies vs Sessions

Both cookies and sessions are used for storing persistent data. But there are differences for sure.

Sessions are stored on server side. Cookies are on the client side.

Sessions are closed when the user closes his browser. For cookies, you can set time that when it will be expired.

Sessions are safe that cookies. Because, since stored on client’s computer, there are ways to modify or manipulate cookies.

Destroying a PHP Session

A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.

Here is the example to unset a single variable −

Trust this instructional exercise helped you a lot, keep reading our various posts for more coding Tricks and Tips. If you like this article do me favor by sharing it with your friends.

Digital Technology Hub