Php Cookies and php Cookies

Source: Internet
Author: User
Tags set cookie unpack

Php Cookies and php Cookies

The example in this article describes the Cookies operation class implemented by PHP and its usage. It is for your reference. The specific analysis is as follows:

I. functions:

1. Save, read, update, and clear cookies.
2. You can set a prefix.
3. Force timeout control.
4. cookies can be strings, arrays, and objects.

Ii. Usage:

Cookies. class. php files are as follows:

<? Php/** Cookies class: Save, read, update, and clear cookies. You can set the prefix. Force timeout. Data can be strings, arrays, and objects. * Date: 2013-12-22 * Author: fdipzone * Ver: 1.0 ** Func: * public set cookie * public get read cookie * public update cookie * public clear cookie * public setPrefix set prefix * public setExpire set expiration time * private authcode encryption/Decryption * private pack package data * private unpack data * private getName get cookie name, added prefix Processing */class Cookies {// class start private $ _ prefix = ''; // cookie prefix private $ _ sec Urekey = 'ekot4 _ Ut0f3XE-fJcpBvRFrg506jpcuJeixezgPNyALm '; // encrypt key private $ _ expire = 3600; // default expire/** initialization * @ param String $ prefix cookie prefix * @ param int $ expire expiration time * @ param String $ securekey cookie secure key */public function _ construct ($ prefix = '', $ expire = 0, $ securekey = '') {if (is_string ($ prefix) & $ prefix! = '') {$ This-> _ prefix = $ prefix;} if (is_numeric ($ expire) & $ expire> 0) {$ this-> _ expire = $ expire;} if (is_string ($ securekey) & $ securekey! = '') {$ This-> _ securekey = $ securekey ;}} /** set cookie * @ param String $ name cookie name * @ param mixed $ value cookie value can be a String, array, object * @ param int $ expire expiration time */public function set ($ name, $ value, $ expire = 0) {$ cookie_name = $ this-> getName ($ name); $ cookie_expire = time () + ($ expire? $ Expire: $ this-> _ expire); $ cookie_value = $ this-> pack ($ value, $ cookie_expire); $ cookie_value = $ this-> authcode ($ cookie_value, 'encoding', $ this-> _ securekey); if ($ cookie_name & $ cookie_value & $ cookie_expire) {setcookie ($ cookie_name, $ cookie_value, $ cookie_expire );}} /** read cookie * @ param String $ name cookie name * @ return mixed cookie value */public function get ($ name) {$ cookie_name = $ this-> g EtName ($ name); if (isset ($ _ COOKIE [$ cookie_name]) {$ cookie_value = $ this-> authcode ($ _ COOKIE [$ cookie_name], 'decode', $ this-> _ securekey); $ cookie_value = $ this-> unpack ($ cookie_value); return isset ($ cookie_value [0])? $ Cookie_value [0]: null;} else {return null;}/** update cookie. Only content is updated, to update the expiration time, use the set Method * @ param String $ name cookie name * @ param mixed $ value cookie value * @ return boolean */public function update ($ name, $ value) {$ cookie_name = $ this-> getName ($ name); if (isset ($ _ COOKIE [$ cookie_name]) {$ old_cookie_value = $ this-> authcode ($ _ COOKIE [$ cookie_name], 'decode', $ this-> _ securekey); $ old_cookie_value = $ t His-> unpack ($ old_cookie_value); if (isset ($ old_cookie_value [1]) & $ old_cookie_vlaue [1]> 0) {// obtain the previous expiration time $ cookie_expire = $ old_cookie_value [1]; // update data $ cookie_value = $ this-> pack ($ value, $ cookie_expire ); $ cookie_value = $ this-> authcode ($ cookie_value, 'enabled', $ this-> _ securekey); if ($ cookie_name & $ cookie_value & $ cookie_expire) {setcookie ($ cookie_name, $ cookie_value, $ cookie_expire); return tru E ;}}return false;}/** clear cookie * @ param String $ name cookie name */public function clear ($ name) {$ cookie_name = $ this-> getName ($ name); setcookie ($ cookie_name );} /** set the prefix * @ param String $ prefix cookie prefix */public function setPrefix ($ prefix) {if (is_string ($ prefix) & $ prefix! = '') {$ This-> _ prefix = $ prefix;}/** set the expiration time * @ param int $ expire cookie expire */public function setExpire ($ expire) {if (is_numeric ($ expire) & $ expire> 0) {$ this-> _ expire = $ expire ;}} /** get cookie name * @ param String $ name * @ return String */private function getName ($ name) {return $ this-> _ prefix? $ This-> _ prefix. '_'. $ name: $ name;}/** pack * @ param Mixed $ data * @ param int $ expire expiration time used to determine * @ return */private function pack ($ data, $ expire) {if ($ data = '') {return'';} $ cookie_data = array (); $ cookie_data ['value'] = $ data; $ cookie_data ['expire '] = $ expire; return json_encode ($ cookie_data);}/** unpack * @ param Mixed $ data * @ return array (data, expiration time) */private function unpack ($ data ){ If ($ data = '') {return array ('', 0) ;}$ cookie_data = json_decode ($ data, true ); if (isset ($ cookie_data ['value']) & isset ($ cookie_data ['expire ']) {if (time () <$ cookie_data ['expire']) {// return array ($ cookie_data ['value'], $ cookie_data ['expire ']);} return array ('', 0 );} /** encrypt/decrypt data * @ param String $ str original text or ciphertext * @ param String $ operation ENCODE or DECODE * @ return String return the plaintext ciphertext */private Function authcode ($ string, $ operation = 'decode') {$ ckey_length = 4; // random key length value: 0-32; $ key = $ this-> _ securekey; $ key = md5 ($ key); $ keya = md5 (substr ($ key, 0, 16); $ keyb = md5 (substr ($ key, 16, 16); $ keyc = $ ckey_length? ($ Operation = 'decode '? Substr ($ string, 0, $ ckey_length): substr (md5 (microtime (),-$ ckey_length): ''; $ cryptkey = $ keya. md5 ($ keya. $ keyc); $ key_length = strlen ($ cryptkey); $ string = $ operation = 'decode '? Base64_decode (substr ($ string, $ ckey_length): sprintf ('% 010d', 0 ). substr (md5 ($ string. $ keyb), 0, 16 ). $ string; $ string_length = strlen ($ string); $ result = ''; $ box = range (0,255); $ rndkey = array (); for ($ I = 0; $ I <= 255; $ I ++) {$ rndkey [$ I] = ord ($ cryptkey [$ I % $ key_length]);} for ($ j = $ I = 0; I I <256; $ I ++) {$ j = ($ j + $ box [$ I] + $ rndkey [$ I]) % 256; $ tmp = $ box [$ I]; $ box [$ I] = $ box [$ j]; $ box [$ J] = $ tmp;} for ($ a = $ j = $ I = 0; $ I <$ string_length; $ I ++) {$ a = ($ a + 1) % 256; $ j = ($ j + $ box [$ a]) % 256; $ tmp = $ box [$ a]; $ box [$ a] = $ box [$ j]; $ box [$ j] = $ tmp; $ result. = chr (ord ($ string [$ I]) ^ ($ box [($ box [$ a] + $ box [$ j]) % 256]);} if ($ operation = 'decode') {if (substr ($ result, 0, 10) = 0 | substr ($ result, 0, 10) -time ()> 0) & substr ($ result, 10, 16) = substr (md5 (substr ($ result, 26 ). $ keyb), 0, 16) {return substr ($ result, 26) ;}else {return '';}} else {return $ keyc. str_replace ('=', '', base64_encode ($ result) ;}}// class end?>

The demo. php sample program is as follows:

<? Php require 'cookies. class. php'; $ type = isset ($ _ GET ['type'])? Strtolower ($ _ GET ['type']): ''; if (! In_array ($ type, array ('set', 'get', 'update', 'clear') {exit ('Type not exists ');} $ obj = new Cookies ('member', 10); // obj switch ($ type) {case 'set ': // set $ data = array ('name' => 'fdipzone ', 'gender' => 'male'); $ obj-> set ('me', $ data, 5); echo 'set cookies '; break; case 'get': // read $ result = $ obj-> get ('me'); echo' <pre> '; print_r ($ result); echo '</pre>'; echo 'get cookies '; break; case 'update' : // Update $ data = array ('name' => 'angelababy', 'gender' => 'female '); $ flag = $ obj-> update ('me', $ data); if ($ flag) {echo 'Update cookies success ';} else {echo 'Update cookies false';} break; case 'clear': // clear $ obj-> clear ('me'); echo 'clear cookies '; break;}?>

Click here to download the complete instance source code in this article.

I hope this article will help you with PHP programming.


In php, how does one set multiple values for cookies? Like asp, multiple values can be set.

<? Php
// Set the cookies
Setcookie ("cookie [three]", "cookiethree ");
Setcookie ("cookie [two]", "cookietwo ");
Setcookie ("cookie [one]", "cookieone ");

// After the page reloads, print them out
If (isset ($ _ COOKIE ['cookies']) {
Foreach ($ _ COOKIE ['cooker'] as $ name => $ value ){
Echo "$ name: $ value <br/> \ n ";
}
}
?>

Example in the manual

How does PHP read COOKIES?

[IT168 technical documentation] Cookies must be assigned a value before the server sends any content to the client's browser. To do this, the cookie settings must be placed in the <HEAD Tag: <? Phpsetcookie ("CookieID", $ USERID );? <HTML <BODY </HTML setcookie function has six parameters separated by commas:
Cookie name, which is a string such as "CookieID ". Colon, comma, and space are not allowed. This parameter is required, and all other parameters are optional. If only this parameter is provided, the cookie will be deleted.
Cookie value, usually a string variable, for example, $ USERID. You can also assign? To skip the value setting.
The time when the cookie expires. If it is omitted (or assigned to zero value), the cookie will expire after the session ends. This parameter can be an absolute time, represented by DD-Mon-yy hh: MM: SS, for example, "24-Nov-99 08:26:00 ". It is more commonly used to set a relative time. This is implemented through the time () function or the mktime function. For example, time () + 3600 will invalidate the cookie after one hour.
A path used to match the cookie. When multiple cookie settings with the same name exist on a server, this parameter is required to avoid confusion. The effect of using the "/" path is the same as that of Omitting this parameter. Note that the cookie definition of Netscape places the domain name in front of the path, while PHP is opposite.
The server domain name is also used to match the cookie. Note that a point (.) must be placed before the Domain Name of the server (.). For example, ".friendshipcenter.com ". Because the parameter is unacceptable unless more than two vertices exist.
Cookie security level, which is an integer. 1 indicates that the cookie can only be transmitted over a "secure" network. 0 or omitted indicates that any type of network can be

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.