欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

一个用于处理cookie的php类

程序员文章站 2024-02-17 20:08:19
...
  1. 登录
  2. 注册
  3. 订阅RSS
  4. 网站地图
  5. 脚本分享网
  6. // cookieClass
  7. // Copyright (C) 2005 JRSofty Programming.
  8. // http://jrsofty1.stinkbugonline.com
  9. // Licensed under GNU/GPL
  10. class cookieClass{
  11. var $cName = '';
  12. var $cTime = '';
  13. var $cSerialize = false;
  14. var $cPath = '';
  15. function cookieClass($cookieName, $cookieTimeout, $cookieSerialize = false, $cookiePath = "/"){
  16. $this->cName = $cookieName;
  17. $this->cTime = $cookieTimeout;
  18. $this->cSerialize = $cookieSerialize;
  19. $this->cPath = $cookiePath;
  20. // This should fix the issue if you have cookies set and THEN turn on the serialization.
  21. $iname = $this->cName . "_S";
  22. if($this->cSerialize && !isset($_COOKIE[$iname])){
  23. $cookArr = array();
  24. foreach($_COOKIE as $name=>$val){
  25. if(strpos($name,$this->cName) !== false ){ // make sure it is a cookie set by this application
  26. $subname = substr($name,strlen($this->cName) + 1);
  27. $cookArr[$subname] = $val;
  28. $this->KillCookie($name);
  29. }
  30. }
  31. $this->WriteCookie($cookArr);
  32. }
  33. // This is the opposite from above. changes a serialized cookie to multiple cookies without loss of data
  34. if(!$this->cSerialize && isset($_COOKIE[$iname])){
  35. $cookArr = unserialize($_COOKIE[$iname]);
  36. $this->KillCookie($iname);
  37. $this->WriteCookie($cookArr);
  38. }
  39. }
  40. function DestroyAllCookies(){
  41. foreach($_COOKIE as $name=>$val){
  42. if(strpos($name,$this->cName) !== false){
  43. $_COOKIE[$name] = NULL;
  44. $this->KillCookie($name);
  45. }
  46. }
  47. }
  48. function ReadCookie($item){
  49. if($this->cSerialize){
  50. $name = $this->cName . "_S";
  51. if(isset($_COOKIE[$name])){
  52. // handle the cookie as a serialzied variable
  53. $sCookie = unserialize($_COOKIE[$name]);
  54. if(isset($sCookie[$item])){
  55. return $sCookie[$item];
  56. }else{
  57. return NULL;
  58. }
  59. }else{
  60. return NULL;
  61. }
  62. }else{
  63. $name = $this->cName . "_" . $item;
  64. if(isset($_COOKIE[$name])){
  65. // handle the item as separate cookies
  66. return $_COOKIE[$name];
  67. }else{
  68. return NULL;
  69. }
  70. }
  71. }
  72. function KillCookie($cName){
  73. $tStamp = time() - 432000;
  74. setcookie($cName,"",$tStamp,$this->cPath);
  75. }
  76. function WriteCookie($itemArr){
  77. if($this->cSerialize){
  78. $sItems = serialize($itemArr);
  79. $name = $this->cName . "_S";
  80. $_COOKIE[$name] = $sItems;
  81. $tStamp = time() + $this->cTime;
  82. setcookie($name,$sItems,$tStamp,$this->cPath);
  83. }else{
  84. $tStamp = time() + $this->cTime;
  85. foreach($itemArr as $nam=>$val){
  86. $name = $this->cName . "_" . $nam;
  87. $_COOKIE[$name] = $val;
  88. setcookie($name,$val,$tStamp,$this->cPath);
  89. }e
  90. }
  91. }
  92. }
  93. ?>
复制代码

cookie, php