Session [php]

Source: Internet
Author: User
Tags temporary file storage
Start session-register session-use session-delete session

1. Start a session

Session_start ()

Use the session_register () function to create a session

The session_register () function is used to implicitly start a session by logging on to a variable for the session, but requires the option of the php. ini file to set the register_globals command to on,

Then restart the Apache server.

Note: When you call session_register (), you do not need to call the session_start () function. PHP will implicitly call the session_start () function after registering the variable.

2. Register a session

After the SESSION is started, all sessions are saved in $ _ SESSION. It is easy to create a SESSION variable through the array $ _ SESSION, as long as you directly add elements to the array.

<? Php

Session_start (); // start the session

$ _ SESSION ["admin"] = null; // lives an admin variable and assigns a null value.

?>

3. Use sessions

First, determine whether the SESSION variable has a session id. If it does not exist, create a SESSION and enable it to access the SESSION through the Global Array $ _ SESSION. If so, the session variable is loaded for use.

For example, if the Session variable of the user name is null or not, copy it to $ myvalue,

<?php

if(!empty($_SESSION['session_name']))

  $myvalue = $_SESSION['session_name'];  

?>

4. delete a session

(1) Delete a single session

When unset () is used, but the unset ($ _ SESSION) function cannot be used, the global variable $ _ SESSION is destroyed and cannot be recovered. You cannot register the $ _ SESSION variable.

unset($_SESSION['user']);

(2) Delete multiple sessions

$_SESSION = array();

(3) end the session

session_destroy();

Set the session time

1. The client does not disable cookie

(1) session_set_cookie_params () must be called before session_start ()

<? Php
$ Time = 1*60; // set the Session expiration time
Session_set_cookie_params ($ time); // use the Function
Session_start (); // initialize the Session
$ _ SESSION [username] = 'Mr ';
?>

Note: This function is not recommended for Some browsers.

(2) Use Setcookie ()

<? Php

Session_start ();

$ Time = 1*60; // specify the Session expiration time, which is 1 minute.

Setcookie (session_name (), session_id (), time () + $ time, "/"); // use setcookie () to manually set the Session expiration time

$ _ SESSION ['user'] = 'Mr ';

?>

2. The client disables cookies.

(1) Open the Cookie before login. Many forums do this.

(2) Hide the form and pass session_id through the GET method (commonly used)

(3) Use session_id for file or database storage and manually call it during page Transfer

 


============================================ Cut ======================================

Session advanced application

1. Session temporary file

Session_save_path () Stores session temporary files, which can alleviate server efficiency reduction and slow Site Opening problems caused by temporary file storage.

Example:

<? Php
$ Path = './tmp/'; // sets the session storage path.
Session_save_path ($ path );
Session_start (); // initialize the session
$ _ SESSION [username] = true;
Echo "Session file name: sess _", session_id ();
?>

Note:Session_save_path () is between session_start () functions.

 


2. Session cache

Session cache stores the content in the Temporary Internet Files folder of the IE client. You can set the cache time to read the cached content next time to speed up.

The Session cache uses the session_cache_limiter () function.

string session_cache_limiter([string cache_limiter])

The cache_limiter parameter is public or private. At the same time, the session cache is not displayed on the server but on the client.

Cache Time, using the session_cache_expire () function

int session_cache_expire([int new_cache_expire])

Example:

<?php
session_cache_limiter('private');
$cache_limit = session_cache_limiter();

session_cache_expire(30);
$cache_expire = session_cache_expire();

session_start();
?>

3. session database storage

Session_set_save_handler () function

bool session_set_save_handler(string open, string close, string read, string write, string destroy, string gc)
Parameters Description
Open (save_path, session_name) Find the session storage address and remove the variable
Close () No parameter is required. Shut down the database.
Read (key) Reads the session key value. The key corresponds to session_id.
Write (key, data) Data corresponds to the set session variable.
Destroy (key) Cancels the session key value corresponding to the session
Gc (expiry_time) Clear expired session records

Example:

<? Phpfunction _ session_open ($ save_path, $ session_name) {global $ handle; $ handle = mysql_connect ('localhost', 'root', 'root ') or die ('database connection failed'); // connect to MYSQL database mysql_select_db ('db _ database11', $ handle) or die ('database does not have this database name '); // find the database return (true);} function _ session_close () {global $ handle; mysql_close ($ handle); return (true);} function _ session_read ($ key) {global $ handle; // global variable $ handle connects to the database $ time = time (); // sets the current time $ SQL = "Select session_data from tb_session where session_key = '$ key' and session_time> $ time"; $ result = mysql_query ($ SQL, $ handle ); $ row = mysql_fetch_array ($ result); if ($ row) {return ($ row ['session _ data']); // return the Session name and content} else {return (false) ;}} function _ session_write ($ key, $ data) {global $ handle; $ time = 60*60; // set the expiration time $ lapse_time = time () + $ time; // obtain the Unix timestamp $ SQL = "select session_data from tb_session w Here session_key = '$ key' and session_time> $ lapse_time "; $ result = mysql_query ($ SQL, $ handle); if (mysql_num_rows ($ result) = 0) // No result {$ SQL = "insert into tb_session values ('$ key',' $ data', $ lapse_time )"; // Insert the database SQL statement $ result = mysql_query ($ SQL, $ handle);} else {$ SQL = "update tb_session set session_key = '$ key ', session_data = '$ data', session_time = $ lapse_time where session_key =' $ key' "; // modify the database SQL statement $ Result = mysql_query ($ SQL, $ handle);} return ($ result);} function _ session_destroy ($ key) {global $ handle; $ SQL = "delete from tb_session where session_key = '$ key'"; // delete a database SQL statement $ result = mysql_query ($ SQL, $ handle ); return ($ result);} function _ session_gc ($ expiry_time) {global $ handle; $ lapse_time = time (); // assign the parameter $ expiry_time to the current timestamp $ SQL = "delete from tb_session where expiry_time <$ lapse_time"; // delete the database SQL statement $ Result = mysql_query ($ SQL, $ handle); return ($ result);} session_set_save_handler ('_ session_open', '_ session_close', '_ session_read ', '_ session_write', '_ session_destroy', '_ session_gc'); session_start (); $ _ SESSION ['user'] = 'Mr '; $ _ SESSION ['pwd'] = 'mrsoft ';?>

============================================ Cut ======================================

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.