Home Backend Development PHP Tutorial php Cookies operation class (with source code)

php Cookies operation class (with source code)

Jul 25, 2016 am 08:55 AM

  1. /** Cookies class Save, read, update, clear cookie data. Prefix can be set. Forced timeout. Data can be strings, arrays, objects, etc.
  2. * Date: 2013-12-22
  3. * Author: fdipzone
  4. * Ver: 1.0
  5. * Edit: bbs.it-home.org
  6. * Func:
  7. * public set Set cookie
  8. * public get Read cookie
  9. * public update update cookie
  10. * public clear clear cookie
  11. * public setPrefix set prefix
  12. * public setExpire set expiration time
  13. * private authcode encryption/decryption
  14. * private pack pack data
  15. * private unpack unpack data
  16. * private getName get cookie name, add prefix processing
  17. */
  18. class Cookies{ // class start
  19. private $_prefix = ''; // cookie prefix
  20. private $_securekey = 'ekOt4_Ut0f3XE-fJcpBvRFrg506jpcuJeixezgPNyALm'; // encrypt key
  21. private $_expire = 3600 ; // default expire
  22. /**Initialization
  23. * @param String $prefix cookie prefix
  24. * @param int $expire expiration time
  25. * @param String $securekey cookie secure key
  26. */
  27. public function __construct($prefix='', $expire=0, $securekey=''){
  28. if(is_string($prefix) && $prefix !=''){
  29. $this->_prefix = $prefix;
  30. }
  31. if(is_numeric($expire) && $expire>0){
  32. $this->_expire = $expire;
  33. }
  34. if(is_string($securekey) && $securekey!=''){
  35. $this->_securekey = $securekey;
  36. }
  37. }
  38. /**Set cookie
  39. * @param String $name cookie name
  40. * @param mixed $value cookie value can be a string, array, object, etc.
  41. * @param int $expire expiration time
  42. */
  43. public function set($name, $ value, $expire=0){
  44. $cookie_name = $this->getName($name);
  45. $cookie_expire = time() + ($expire? $expire : $this->_expire);
  46. $cookie_value = $this->pack($value, $cookie_expire);
  47. $cookie_value = $this->authcode($cookie_value, 'ENCODE', $this->_securekey);
  48. if($cookie_name && $cookie_value && $cookie_expire){
  49. setcookie($cookie_name, $cookie_value, $cookie_expire);
  50. }
  51. }
  52. /**读取cookie
  53. * @param String $name cookie name
  54. * @return mixed cookie value
  55. */
  56. public function get($name){
  57. $cookie_name = $this-> ;getName($name);
  58. if(isset($_COOKIE[$cookie_name])){
  59. $cookie_value = $this->authcode($_COOKIE[$cookie_name], 'DECODE', $this-> _securekey);
  60. $cookie_value = $this->unpack($cookie_value);
  61. return isset($cookie_value[0])? $cookie_value[0] : null;
  62. }else{
  63. return null;
  64. }
  65. }
  66. /**Update cookie, only update the content. If you need to update the expiration time, please use the set method
  67. * @param String $name cookie name
  68. * @param mixed $value cookie value
  69. * @return boolean
  70. */
  71. public function update($name, $value){
  72. $cookie_name = $this->getName($name);
  73. if(isset($_COOKIE[$cookie_name] )){
  74. $old_cookie_value = $this->authcode($_COOKIE[$cookie_name], 'DECODE', $this->_securekey);
  75. $old_cookie_value = $this->unpack($old_cookie_value);
  76. if(isset($old_cookie_value[1]) && $old_cookie_vlaue[1]>0){ // Get the previous expiration time
  77. $cookie_expire = $old_cookie_value[1];
  78. // Update data
  79. $cookie_value = $ this->pack($value, $cookie_expire);
  80. $cookie_value = $this->authcode($cookie_value, 'ENCODE', $this->_securekey);
  81. if($cookie_name && $cookie_value && $ cookie_expire){
  82. setcookie($cookie_name, $cookie_value, $cookie_expire);
  83. return true;
  84. }
  85. }
  86. }
  87. return false;
  88. }
  89. /**清除cookie
  90. * @param String $name cookie name
  91. */
  92. public function clear($name) {
  93. $cookie_name = $this->getName($name);
  94. setcookie($cookie_name);
  95. }
  96. /**Set prefix
  97. * @param String $prefix cookie prefix
  98. */
  99. public function setPrefix($prefix){
  100. if(is_string($ prefix) && $prefix!=''){
  101. $this->_prefix = $prefix;
  102. }
  103. }
  104. /**Set expiration time
  105. * @param int $expire cookie expire
  106. */
  107. public function setExpire($expire){
  108. if(is_numeric($expire) && $expire>0){
  109. $this->_expire = $expire;
  110. }
  111. }
  112. /**获取cookie name
  113. * @param String $name
  114. * @return String
  115. */
  116. private function getName($name){
  117. return $this->_prefix? $this->_prefix.'_'.$name : $name;
  118. }
  119. /**pack
  120. * @param Mixed $data data
  121. * @param int $expire expiration time used for judgment
  122. * @return
  123. */
  124. private function pack($data, $expire){
  125. if($data===''){
  126. return '';
  127. }
  128. $cookie_data = array();
  129. $cookie_data['value'] = $data;
  130. $cookie_data['expire'] = $expire;
  131. return json_encode($cookie_data);
  132. }
  133. /**unpack
  134. * @param Mixed $data data
  135. * @return array(data, expiration time)
  136. */
  137. private function unpack($data){
  138. if($data===''){
  139. return array('', 0);
  140. }
  141. $cookie_data = json_decode($data, true);
  142. if(isset($cookie_data['value']) && isset($cookie_data['expire'])){
  143. if(time()<$cookie_data['expire']){ // 未过期
  144. return array($cookie_data['value'], $cookie_data['expire']);
  145. }
  146. }
  147. return array('', 0);
  148. }
  149. /**Encrypt/decrypt data
  150. * @param String $str Original text or ciphertext
  151. * @param String $operation ENCODE or DECODE
  152. * @return String Return plaintext or ciphertext according to settings
  153. */
  154. private function authcode($string, $operation = 'DECODE'){
  155. $ckey_length = 4; // 随机密钥长度 取值 0-32;
  156. $key = $this->_securekey;
  157. $key = md5($key);
  158. $keya = md5(substr($key, 0, 16));
  159. $keyb = md5(substr($key, 16, 16));
  160. $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
  161. $cryptkey = $keya.md5($keya.$keyc);
  162. $key_length = strlen($cryptkey);
  163. $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', 0).substr(md5($string.$keyb), 0, 16).$string;
  164. $string_length = strlen($string);
  165. $result = '';
  166. $box = range(0, 255);
  167. $rndkey = array();
  168. for($i = 0; $i <= 255; $i++) {
  169. $rndkey[$i] = ord($cryptkey[$i % $key_length]);
  170. }
  171. for($j = $i = 0; $i < 256; $i++) {
  172. $j = ($j + $box[$i] + $rndkey[$i]) % 256;
  173. $tmp = $box[$i];
  174. $box[$i] = $box[$j];
  175. $box[$j] = $tmp;
  176. }
  177. for($a = $j = $i = 0; $i < $string_length; $i++) {
  178. $a = ($a + 1) % 256;
  179. $j = ($j + $box[$a]) % 256;
  180. $tmp = $box[$a];
  181. $box[$a] = $box[$j];
  182. $box[$j] = $tmp;
  183. $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
  184. }
  185. if($operation == 'DECODE') {
  186. if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
  187. return substr($result, 26);
  188. } else {
  189. return '';
  190. }
  191. } else {
  192. return $keyc.str_replace('=', '', base64_encode($result));
  193. }
  194. }
  195. } // class end
  196. ?>
复制代码

2,演示示例 demo.php

  1. require 'Cookies.class.php';
  2. $type = isset($_GET['type'])? strtolower($_GET['type']) : '';
  3. if(!in_array($type, array('set','get','update','clear'))){
  4. exit('type not exists');
  5. }
  6. $obj = new Cookies('member', 10); // obj
  7. switch($type){
  8. case 'set': // 设置
  9. $data = array(
  10. 'name' => 'fdipzone',
  11. 'gender' => 'male'
  12. );
  13. $obj->set('me', $data, 5);
  14. echo 'set cookies';
  15. break;
  16. case 'get': // 读取
  17. $result = $obj->get('me');
  18. echo '
    ';  </li>
    <li>        print_r($result);  </li>
    <li>        echo '
    ';
  19. echo 'get cookies';
  20. break;
  21. case 'update': // 更新
  22. $data = array(
  23. 'name' => 'angelababy',
  24. 'gender' => 'female'
  25. );
  26. $flag = $obj->update('me', $data);
  27. if($flag){
  28. echo 'update cookies success';
  29. }else{
  30. echo 'update cookies false';
  31. }
  32. break;
  33. case 'clear': // 清除
  34. $obj->clear('me');
  35. echo 'clear cookies';
  36. break;
  37. }
  38. ?>
复制代码

附,PHP Cookies操作类的源码下载地址



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

See all articles