This article describes the differences and usage of session and cookie in php, and explains through code. Cookie setting method
Setcookie ("name", 'hangsan'); setcookie ("name", 'hangsan', time () + 60 ); // Set the cookie validity period to 60 s // setcookie ("visittime", date ("y-m-d H: I: s"), time () + 60 ); // Set the variable for saving the cookie expiration time // read cokie method $ name =$ _ COOKIE ["name"}; // delete the cookie method setcookie ("name ","", time ()-1); // Set the cookie () time to the current time minus 1. the time () function returns the current timestamp in seconds, after the expiration time is reduced by 1 second, the previous time is obtained. therefore, to delete the cookie // delete cookiez, you only need to set the second parameter in the setcookie () function to a null value, set the cookie expiration time of the third parameter to less than the current time of the system.
Method 1
Session_start (); $ _ SESSION ["admin"] = $ name; $ _ SESSION ['user'] = $ _ POST ['user']; // Set the cookie method 2session_register () // You do not need to call session_start () when using this method. PHP will call the session_start () function implicitly after registering the variable, but requires setting php. the INI file option calls the session_start () function; // session use case if (! Empty ($ _ SESSION ['session _ name']) {// equivalent to isset ($ _ session ['think'] ['name']); $ myvalue = $ _ SESSION ['session _ name'];}
Delete a session
unset($_SESSION['user']);
// Delete multiple sessions
$ _ SESSION = array (); ends the current SESSION; unset ($ _ session ['user']); // equivalent to SESSION ('name', null ); session_destroy (); // delete all current session variables // The session setting time session_start (); session_set_cookie_params ($ time); // This method is not recommended, and some browsers may have problems
Method 2
Session_start (); $ time = 1*60; // The setcookie (session_name (), time () + $ time) expires after one minute in session );
The biggest difference between session and cookie is:
1. session stores session information on the server and transmits client information through a session ID. after the server receives the session ID, provide related sesion information resources based on this ID
2. cookies store all information on the client as text and are managed and maintained by the browser.
3. since session is stored on the server, all remote users cannot modify the content of the session file, and the cookie
For client-side storage, all sessions are much safer than cookies. of course, there are many advantages, such as easy control and custom storage (stored in the database )...
The above are the differences between session and cookie in php and the usage details. For more information, see other related articles in the first PHP community!