Session start and session destroy in php

Session start and session destroy in php

Сессии представляют набор переменных, которые хранятся на сервере (либо часть на сервере, а часть — в cookie браузера) и которые относятся только к текущему пользователю. В какой-то степени сессии являются альтернативой кукам в плане сохранения данных о пользователе.

Для запуска сессии необходимо вызвать функцию session_start() . Она должна вызываться до отправки ответа пользователю:

При запуске сессии с помощью функции session_start() , если пользователь первый раз заходит на сайт, PHP назначает ему уникальный идентификатор сессии. Этот идентификатор с помощью cookie, которые по умолчанию называются «PHPSESSID», сохраняется в браузере пользователя. С помощью этого идентификатора пользователь ассоциируется с данными сессии. Если для пользователя уже установлена сессия, то данная функция продлевает текущую сессию вместо установки новой.

С помощью специальных функций мы можем получить идентификатор сессии:

session_start(); echo session_id(); // идентификатор сессии echo session_name(); // имя - PHPSESSID

То же значение мы могли бы получить, обратившись к cookie напрямую:

Затем для сохранения или получения данных в сессии надо использовать глобальный ассоциативный массив $_SESSION . Сохранение переменной в сессии:

$_SESSION["имя_переменной"] = значение;

Получение сохраненного значения:

$переменная = $_SESSION["имя_переменной"];

Сохранение данных в сессии

Запустим сессию и сохраним в ней значения:

После установки сессии в браузере мы сможем заметить установку специальной куки, которая по умолчанию называется «PHPSESSID»:

Сессии в PHP и session_start и <img decoding=

Теперь получим эти значения и выведем на страницу:

session_start(); if (isset($_SESSION["name"]) && isset($_SESSION["age"])) < $name = $_SESSION["name"]; $age = $_SESSION["age"]; echo "Name: $name 
Age: $age"; >

Удаление данных сессии

Сессия уничтожается с закрытием браузера, однако мы также можем программно удалить либо какие-то отдельные, либо все данные сессии.

Для удаления одной переменной из сессии применяется функция unset() :

session_start(); unset($_SESSION["age"]); // удаляем из сессии переменную "age"

Удалить все данные сессии можно с помощью функции session_destroy() :

session_start(); session_destroy();

Источник

Функции для работы с сессиями

Be aware of the fact that absolute URLs are NOT automatically rewritten to contain the SID.

Of course, it says so in the documentation (‘Passing the Session Id’) and of course it makes perfectly sense to have that restriction, but here’s what happened to me:
I have been using sessions for quite a while without problems. When I used a global configuration file to be included in all my scripts, it contained a line like this:

which was used to make sure that all automatically generated links had the right prefix (just like $cfg[‘PmaAbsoluteUri’] works in phpMyAdmin). After introducing that variable, no link would pass the SID anymore, causing every script to return to the login page. It took me hours (!!) to recognize that this wasn’t a bug in my code or some misconfiguration in php.ini and then still some more time to find out what it was. The above restriction had completely slipped from my mind (if it ever was there. )

Читайте также:  Reading array values in php

Skipping the ‘http:’ did the job.

OK, it was my own mistake, of course, but it just shows you how easily one can sabotage his own work for hours. Just don’t do it 😉

Sessions and browser’s tabs

May you have noticed when you open your website in two or more tabs in Firefox, Opera, IE 7.0 or use ‘Control+N’ in IE 6.0 to open a new window, it is using the same cookie or is passing the same session id, so the another tab is just a copy of the previous tab. What you do in one will affect the another and vice-versa. Even if you open Firefox again, it will use the same cookie of the previous session. But that is not what you need mostly of time, specially when you want to copy information from one place to another in your web application. This occurs because the default session name is «PHPSESSID» and all tabs will use it. There is a workaround and it rely only on changing the session’s name.

Put these lines in the top of your main script (the script that call the subscripts) or on top of each script you have:

if( version_compare ( phpversion (), ‘4.3.0’ )>= 0 ) <
if(! ereg ( ‘^SESS4+$’ , $_REQUEST [ ‘SESSION_NAME’ ])) <
$_REQUEST [ ‘SESSION_NAME’ ]= ‘SESS’ . uniqid ( » );
>
output_add_rewrite_var ( ‘SESSION_NAME’ , $_REQUEST [ ‘SESSION_NAME’ ]);
session_name ( $_REQUEST [ ‘SESSION_NAME’ ]);
>
?>

How it works:

First we compare if the PHP version is at least 4.3.0 (the function output_add_rewrite_var() is not available before this release).

After we check if the SESSION_NAME element in $_REQUEST array is a valid string in the format «SESSIONxxxxx», where xxxxx is an unique id, generated by the script. If SESSION_NAME is not valid (ie. not set yet), we set a value to it.

uniqid(») will generate an unique id for a new session name. It don’t need to be too strong like uniqid(rand(),TRUE), because all security rely in the session id, not in the session name. We only need here a different id for each session we open. Even getmypid() is enough to be used for this, but I don’t know if this may post a treat to the web server. I don’t think so.

output_add_rewrite_var() will add automatically a pair of ‘SESSION_NAME=SESSxxxxx’ to each link and web form in your website. But to work properly, you will need to add it manually to any header(‘location’) and Javascript code you have, like this:

The last function, session_name() will define the name of the actual session that the script will use.

So, every link, form, header() and Javascript code will forward the SESSION_NAME value to the next script and it will know which is the session it must use. If none is given, it will generate a new one (and so, create a new session to a new tab).

May you are asking why not use a cookie to pass the SESSION_NAME along with the session id instead. Well, the problem with cookie is that all tabs will share the same cookie to do it, and the sessions will mix anyway. Cookies will work partially if you set them in different paths and each cookie will be available in their own directories. But this will not make sessions in each tab completly separated from each other. Passing the session name through URL via GET and POST is the best way, I think.

Читайте также:  Java для eclipse ide

Источник

PHP Sessions

A session is a way to store information (in variables) to be used across multiple pages.

Unlike a cookie, the information is not stored on the users computer.

What is a PHP Session?

When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn’t maintain state.

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.

Tip: If you need a permanent storage, you may want to store the data in a database.

Start a PHP Session

A session is started with the session_start() function.

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

Now, let’s create a new page called «demo_session1.php». In this page, we start a new PHP session and set some session variables:

Example

// Set session variables
$_SESSION[«favcolor»] = «green»;
$_SESSION[«favanimal»] = «cat»;
echo «Session variables are set.»;
?>

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

Get PHP Session Variable Values

Next, we create another page called «demo_session2.php». From this page, we will access the session information we set on the first page («demo_session1.php»).

Notice that session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page ( session_start() ).

Also notice that all session variable values are stored in the global $_SESSION variable:

Example

// Echo session variables that were set on previous page
echo «Favorite color is » . $_SESSION[«favcolor»] . «.
«;
echo «Favorite animal is » . $_SESSION[«favanimal»] . «.»;
?>

Another way to show all the session variable values for a user session is to run the following code:

Example

How does it work? How does it know it’s me?

Most sessions set a user-key on the user’s computer that looks something like this: 765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on another page, it scans the computer for a user-key. If there is a match, it accesses that session, if not, it starts a new session.

Modify a PHP Session Variable

To change a session variable, just overwrite it:

Example

// to change a session variable, just overwrite it
$_SESSION[«favcolor»] = «yellow»;
print_r($_SESSION);
?>

Destroy a PHP Session

To remove all global session variables and destroy the session, use session_unset() and session_destroy() :

Example

// remove all session variables
session_unset();

// destroy the session
session_destroy();
?>

Источник

Session in PHP: Creating, Destroying, and Working With Session in PHP

Session in PHP : Creating, Working With, and Destroying a Session

Session in PHP is a way of temporarily storing and making data accessible across all the website pages. It will create a temporary file that stores various session variables and their values. This will be destroyed when you close the website. This file is then available to all the pages of the website to access information about the user.

Читайте также:  Img css styles for sites

You need to set the path for this file using the session.save_path setting from the php.ini file. If you don’t set this path, the session might malfunction.

What Is the Use of Session in PHP?

A session in PHP allows the webserver to get the information about when you started a website, what you were doing, when you closed the website and other related information. It is required because, unlike the PC or mobile, the webserver does not have any information about you. That’s where sessions come into the picture.

These sessions have session variables that store all the necessary information into a temporary file. By default, it will destroy this file when you close the website. Thus, to put it simply, a session in PHP helps in storing information about users and makes the data available to all the pages of a website or application until you close it.

Basics to Advanced — Learn It All!

What Happens When You Start a Session in PHP?

The following things occur when a session is started:

  • It creates a random 32 digit hexadecimal value as an identifier for that particular session. The identifier value will look something like 4af5ac6val45rf2d5vre58sd648ce5f7.
  • It sends a cookie named PHPSESSID to the user’s system. As the name gives out, the PHPSESSID cookie will store the unique session id of the session.
  • A temporary file gets created on the server and is stored in the specified directory. It names the file on the hexadecimal id value prefixed with sess_. Thus, the above id example will be held in a file called sess_4af5ac6val45rf2d5vre58sd648ce5f7.

PHP will access the PHPSESSID cookie and get the unique id string to get session variables’ values. It will then look into its directory for the file named with that string.

When you close the browser or the website, it terminates the session after a certain period of a predetermined time.

How to Start a PHP Session?

You can start a session in PHP by using the session_start() function. This function will, by default, first check for an existing session. If a session already exists, it will do nothing, but it will create one if there’s no pre-existing session available.

To set session variables, you can use the global array variable called $_SESSION[]. The server can then access these global variables until it terminates the session. Now that you know what a session is in PHP and how to start one, it’s time to look at an example and see how it works.

Note: It is always recommended to put the session_start() function as the first line in your code, even before any HTML tags.

Example: How to Start a Session in PHP?

In the example below, you will start a session that will count how many times you have visited a website page. For this, you will create a session variable named counter.

$my_Msg = «This page is visited «. $_SESSION[‘counter’];

$my_Msg .= » time during this session.»;

Источник

Оцените статью