How to start php session

How to start php session

Sessions are a simple way to store data for individual users against a unique session ID. This can be used to persist state information between page requests. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data. The absence of an ID or session cookie lets PHP know to create a new session, and generate a new session ID.

Sessions follow a simple workflow. When a session is started, PHP will either retrieve an existing session using the ID passed (usually from a session cookie) or if no session is passed it will create a new session. PHP will populate the $_SESSION superglobal with any session data after the session has started. When PHP shuts down, it will automatically take the contents of the $_SESSION superglobal, serialize it, and send it for storage using the session save handler.

By default, PHP uses the internal files save handler which is set by session.save_handler. This saves session data on the server at the location specified by the session.save_path configuration directive.

Sessions can be started manually using the session_start() function. If the session.auto_start directive is set to 1 , a session will automatically start on request startup.

Sessions normally shutdown automatically when PHP is finished executing a script, but can be manually shutdown using the session_write_close() function.

Example #1 Registering a variable with $_SESSION .

session_start ();
if (!isset( $_SESSION [ ‘count’ ])) $_SESSION [ ‘count’ ] = 0 ;
> else $_SESSION [ ‘count’ ]++;
>
?>

Example #2 Unregistering a variable with $_SESSION .

Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.

You can’t use references in session variables as there is no feasible way to restore a reference to another variable.

Note:

File based sessions (the default in PHP) lock the session file once a session is opened via session_start() or implicitly via session.auto_start. Once locked, no other script can access the same session file until it has been closed by the first script terminating or calling session_write_close() .

This is most likely to be an issue on Web sites that use AJAX heavily and have multiple concurrent requests. The easiest way to deal with it is to call session_write_close() as soon as any required changes to the session have been made, preferably early in the script. Alternatively, a different session backend that does support concurrency could be used.

User Contributed Notes

Источник

Читайте также:  Цикл с итератором python

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»).

Читайте также:  Как вставить галерею в html

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_start

session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.

When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers. These will either be a built-in save handler provided by default or by PHP extensions (such as SQLite or Memcached); or can be custom handler as defined by session_set_save_handler() . The read callback will retrieve any existing session data (stored in a special serialized format) and will be unserialized and used to automatically populate the $_SESSION superglobal when the read callback returns the saved session data back to PHP session handling.

To use a named session, call session_name() before calling session_start() .

When session.use_trans_sid is enabled, the session_start() function will register an internal output handler for URL rewriting.

Читайте также:  Css has can i use

If a user uses ob_gzhandler or similar with ob_start() , the function order is important for proper output. For example, ob_gzhandler must be registered before starting the session.

Parameters

If provided, this is an associative array of options that will override the currently set session configuration directives. The keys should not include the session. prefix.

In addition to the normal set of configuration directives, a read_and_close option may also be provided. If set to true , this will result in the session being closed immediately after being read, thereby avoiding unnecessary locking if the session data won’t be changed.

Return Values

This function returns true if a session was successfully started, otherwise false .

Changelog

Version Description
7.1.0 session_start() now returns false and no longer initializes $_SESSION when it failed to start the session.

Examples

A basic session example

Example #1 page1.php

$_SESSION [ ‘favcolor’ ] = ‘green’ ;
$_SESSION [ ‘animal’ ] = ‘cat’ ;
$_SESSION [ ‘time’ ] = time ();

After viewing page1.php , the second page page2.php will magically contain the session data. Read the session reference for information on propagating session ids as it, for example, explains what the constant SID is all about.

Example #2 page2.php

echo $_SESSION [ ‘favcolor’ ]; // green
echo $_SESSION [ ‘animal’ ]; // cat
echo date ( ‘Y m d H:i:s’ , $_SESSION [ ‘time’ ]);

Providing options to session_start()

Example #3 Overriding the cookie lifetime

// This sends a persistent cookie that lasts a day.
session_start ([
‘cookie_lifetime’ => 86400 ,
]);
?>

Example #4 Reading the session and closing it

// If we know we don’t need to change anything in the
// session, we can just read and close rightaway to avoid
// locking the session file and blocking other pages
session_start ([
‘cookie_lifetime’ => 86400 ,
‘read_and_close’ => true ,
]);

Notes

Note:

To use cookie-based sessions, session_start() must be called before outputting anything to the browser.

Note:

This function sends out several HTTP headers depending on the configuration. See session_cache_limiter() to customize these headers.

See Also

  • Session Functions
    • session_​abort
    • session_​cache_​expire
    • session_​cache_​limiter
    • session_​commit
    • session_​create_​id
    • session_​decode
    • session_​destroy
    • session_​encode
    • session_​gc
    • session_​get_​cookie_​params
    • session_​id
    • session_​module_​name
    • session_​name
    • session_​regenerate_​id
    • session_​register_​shutdown
    • session_​reset
    • session_​save_​path
    • session_​set_​cookie_​params
    • session_​set_​save_​handler
    • session_​start
    • session_​status
    • session_​unset
    • session_​write_​close

    Источник

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