Session [PHP]

Source: Internet
Author: User
Tags session id setcookie temporary file storage

1. Start the session

Session_Start ()

Creating a session with the Session_register () function

The Session_register () function is used to login a variable for the session implicitly to start the session, but requires the option to php.ini the file, set the register_globals instruction to ON,

Then restart the Apache server.

Note: when calling Session_register (), you do not need to call the Session_Start () function, and PHP will implicitly call the Session_Start () function after registering the variable.

2. Registering a session

After the session is started, it is all saved in $_session. Creating a session variable from an array $_session is easy, as long as you add elements directly to the array.

<?php

Session_Start (); Start session

$_session["admin"] = null; Life an admin variable, and assign null value

?>

3. Using sessions

First, determine if a session variable has a session ID present, create one without being present, and make it accessible through the global array $_session. If present, the session variable is loaded for use by the user.

For example, determine if the session variable is empty, not empty, and copy to $myvalue.

<?php

if (!empty ($_session[' session_name '))

$myvalue = $_session[' session_name ');

?>

4. Delete a session

(1) Delete a single session

Use Unset (), but you cannot use the unset ($_session) function to destroy global variables $_session, cannot be restored, and users can no longer register $_session variables.

unset ($_session[' user ');

(2) Delete multiple sessions

$_session = Array ();

(3) End session

Session_destroy ();

Session setup Time

1. The client does not prohibit cookies

(1) Session_set_cookie_params () must be called before Session_Start ()

<?php
$time = 1*60; Set session Expiration Time
Session_set_cookie_params ($time); Using functions
Session_Start (); Initialize session
$_session[username] = ' Mr ';
?>

Description: This function is not recommended and some browsers have problems.

(2) using Setcookie ()

<?php

Session_Start ();

$time = 1*60; Give the session failure time, 1 minutes

Setcookie (Session_name (), session_id (), time () + $time, "/"); Set session expiration time manually using Setcookie ()

$_session[' user ']= ' Mr ';

?>

2. The client prohibits cookies

(1) Open cookies before logging in, many forums do so

(2) Hide form pass through Get method session_id (Common)

(3) Use file or database storage session_id, manually invoke in Page pass

 

====================== =========== cut ============ line ================

Session Advanced Application

1.Session temp File

Session_save_path () stores session temp files to mitigate server inefficiencies and slow site opening due to temporary file storage

Example:

<?php
$path = './tmp/'; Set Session storage Path
Session_save_path ($path);
Session_Start (); Initialize session
$_session[username] = true;
echo "Session filename is called: Sess_", session_id ();
?>

Note:Session_save_path () between the session_start () functions

 

2.Session Cache

Session cache is to store content in the IE client's temporary Internet Files folder, you can set the cache time, the next time to read the cache content, thereby speeding up.

Session Cache uses the Session_cache_limiter () function

String Session_cache_limiter ([string cache_limiter])

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

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 session storage address, remove variables
Close () Do not require parameters to close the database
Read (key) Read session key value, key corresponds to session_id
Write (Key,data) Where data corresponds to the setting of the session variable
Destroy (Key) Logoff session corresponding session key value
GC (Expiry_time) Clear expired session Record

Example:

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 66676869707172737475 <?phpfunction_session_open($save_path,$session_name){    global$handle;    $handle= mysql_connect(‘localhost‘,‘root‘,‘root‘or die(‘数据库连接失败‘);       // 连接MYSQL数据库    mysql_select_db(‘db_database11‘,$handleordie(‘数据库中没有此库名‘);               // 找到数据库    return(true);}function_session_close(){    global$handle;    mysql_close($handle);    return(true);}function_session_read($key){    global$handle;                         // 全局变量$handle 连接数据库    $time= 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‘]);           // 返回Session名称及内容    }else    {        return(false);    }}function_session_write($key,$data){    global$handle;    $time= 60*60;                                      // 设置失效时间    $lapse_time= time() + $time;                       // 得到Unix时间戳    $sql"select session_data from tb_session where session_key = ‘$key‘ and session_time > $lapse_time";    $result= mysql_query($sql,$handle);    if(mysql_num_rows($result) == 0 )              // 没有结果    {        $sql"insert into tb_session values(‘$key‘,‘$data‘,$lapse_time)";     // 插入数据库sql语句        $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‘";                                               // 修改数据库sql语句        $result= mysql_query($sql,$handle);    }    return($result);}function_session_destroy($key){    global$handle;    $sql"delete from tb_session where session_key = ‘$key‘";                 // 删除数据库sql语句    $result= mysql_query($sql,$handle);    return($result);}function_session_gc($expiry_time){    global$handle;    $lapse_time= time();                                   // 将参数$expiry_time赋值为当前时间戳    $sql"delete from tb_session where expiry_time < $lapse_time"// 删除数据库sql语句    $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‘;?>

Session [PHP]

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.