Introduction to PHP session mechanism and its usage _php skills

Source: Internet
Author: User

When the server creates a session (Session_Start ()), the server creates a sessions file under the specified folder of the server with the name SessionID and sent to the browser as a value for the cookie. Every time the browser comes to the server with this cookie, the server will recognize the change SessionID and find the corresponding session file. A number of key value pairs are stored in the file. The folder in which the session file resides can be modified in the configuration file Php,ini.

Cookies are validated each time the page is requested, and if the user information is stored in the database, a database query is executed at a time, creating an extra burden on the database. Cookies can be modified, so the safety factor is too low.

Sessions are conversations that are stored on the server's face, are relatively secure, and do not have storage-length limitations like cookies. Because the session is stored as a text file on the server side, the client is not afraid to modify session content. In fact, the server-side session file, PHP automatically modify the session file permissions, only the system to read and write permissions, and can not be modified through FTP, so much more secure.

For cookies, suppose we want to verify that the user is logged in, you must save the username and password in the cookie (possibly a MD5 encrypted string) and verify each time the page is requested.

If the username and password are stored in the database, each time a database query is executed, causing an extra burden to the database. Because we can't just do one validation. Why, then?

Because the information in the client Cookie is likely to be modified. If you store $admin variable to indicate whether the user is logged in, the $admin is true to indicate that the login is not logged in, false, the first time after the verification will be $admin equal to true stored in the Cookie, the next time you do not have to verify, this right? Wrong, if someone faked a $admin variable with a value of true does that not immediately take the administrative authority? It's very unsafe.

And the session is different, the session is stored on the server side, the remote user can not modify the contents of the session file, so we could simply store a $admin variable to determine whether to log in, the first validation passed after the set $admin value is true, Later to determine if the value is true, if not, go to the login interface, this can reduce a lot of database operations.

It also reduces the security of passing passwords every time you verify cookies (session validation only needs to be passed once, if you don't use SSL security protocol). Even if the password is MD5 encrypted, it is very easy to intercept.

Session sessions Create a unique session ID for each visitor who opens session sessions to identify the user. The session ID may be stored in a cookie on the user's computer, or it may be passed through a URL. The corresponding session value is stored on the server side, which is the main difference from the cookie, and the security is relatively high.

Create session

To create a session or return an existing one, you must start a session with the Session_Start () function, and the system assigns a session ID:

<?php
session_start ()//This function has no parameters and the return value is true. It is best to put this function first, and there is no output before it, otherwise it will alarm
?>

Register Session variable

Registers a session variable with the Session_register () function, returns TRUE successfully, or returns FALSE.

Syntax: BOOL Session_register (mixed name [, mixed ...])

You can use the Session_register () function to register one or more global session variables under current sessions. The parameter name is the name of the variable you want to join, and success returns the logical value TRUE. You can use the form of $_session[name] or $http_session_vars[name] to take a value or assign a value.

Example:

<?php
session_start ();
$username = "Nostop";
Session_register ("username");
? >

In this example, we registered a variable named username to the session with a value of nostop.

Read session

PHP's built-in $_session variable makes it easy to access settings for session variables.

Example:

<?php
session_start ();
echo "Registered user name:". $_session["username"];  The output registered user name is: nostop
?>

Destroy session

Session_unregister () unregister a single session variable
unset ($_session[' age ')); Used to unregister session variables registered with $_session[' age '
Session_unset () Delete all registered variables
Session_destroy () Unregister all session variables and log out of the entire sessions

Example:

<?php
session_start ();
Session_unregister ("username");  Logout session a variable
session_unset ();     Unregister session Sessions
?>


Check whether a variable is registered as a session variable

Session_is_registered

Syntax: Boobean session_is_registered (string name);

This function checks whether the specified variable is registered in the current session, and the parameter name is the variable name to check. Success returns the logical value TRUE.

Example:

<?php
  session_start ();
  if (!session_is_registered ("gender")) {//Determine whether the current session variable is registered
    session_register ("gender");  Registration variable
  }
  $gender = "female";
  echo $_session[' gender ']; Female
?>


accessing the current session name

Session_name

Syntax: Boolean session_name (string [name]);

This function can get or reset the name of the current session. Without the parameter name, the current session name is obtained, plus the parameter indicates that the session name is set to the parameter name.

Example:

<?php

$sessionName = Session_name ();  Gets the current session name, defaults to PHPSESSID
$sessionID = $_get[$sessionName];  Gets the session ID
session_id ($sessionID);   The session ID obtained using the session_id () setting
?>

Accessing the current session identification number

session_id

Syntax: Boolean session_id (string [id]);

This function can get or reset the identification number of the current session. The absence of a parameter ID means that only the identification number of the current session is obtained, plus the parameter indicates that the session's identification number is set to the newly specified ID.

Set the lifetime of a session

Setcookie: Sends an HTTP cookie to the client.

<?php
  session_start
  //Save a day
  $lifeTime = * 3600;
  Setcookie (Session_name (), session_id (), time () + $lifeTime, "/");
? >

Session_set_cookie_params: Sets the lifetime of the session, which must be called before the session_start () function call.
If the client uses IE 6.0, Session_set_cookie_params (); There are some problems with the function setting cookies, so we call the Setcookie function manually to create the cookie.

Save one day

<?php
$lifeTime = * 3600;
Session_set_cookie_params ($lifeTime);
Session_Start ();
$_session["Admin"] = true;
? >

Set the save path for the session file

Session_save_path (): Must be called before the session_start () function call.

<?php
//Set up a storage directory
$savePath = "./session_save_dir/";
Save one day
$lifeTime = * 3600;
Session_save_path ($savePath);
Session_set_cookie_params ($lifeTime);
Session_Start ();
$_session["Admin"] = true;
? >
 <?php session_start ();
Start session $username = ' nostop ';  Session_register (' username ');  Register a user named Username variable echo ' registered: '. $_session[' username ';  Registered User: Nostop reads the session variable $_session[' age ']=23; Declares a variable named age and assigns the Echo ' Ages: '. $_session[' aged ']; Age: Session_unregister (' username '); Unregister session variable echo $_session[' username ']; Empty echo $_session[' age '];//23 unset ($_session[' age '); Unregister session variable echo ' registered User: '. $_session[' username ']; Empty echo ' Age: '. $_session[' ages ']; Empty?> 

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.