插件69:管理cookie

<?php // Plug-in 69: Manage Cookie
/*
 * 插件說明:
 * 管理Cookie
 * 插件可以給Cookie變量設置值,可以讀取Cookie變量的值,甚至可以刪除cookie變量。
 * 需要以下參數:
 * $action 對cookie採取的動作:設置值,讀取和刪除。
 * $cookie cookie變量名
 * $value cookie變量值
 * $expire cookie變量的有效期限,單位爲妙
 * $path 服務器上cookie路徑
 */
// This is an executable example with additional code supplied
// To obtain just the plug-ins please click on the Download link

$cookie = 'Test';
$value  = '3.1415927';
$expire = 300;
$path   = '/';

$result = PIPHP_ManageCookie('read', $cookie, NULL, NULL, NULL);

if (PIPHP_ManageCookie('set', $cookie, $value, $expire, $path))
   echo "Cookie '$cookie' set to value '$value'";
else echo 'Setting of cookie failed';

echo "<br />The read value of '$cookie' is '$result'";
echo '<br />(Reload to read the cookie back).';

function PIPHP_ManageCookie($action, $cookie, $value, $expire,
   $path)
{
   // Plug-in 69: Manage Cookie
   //
   // This plug-in provides three ways of interacting with
   // cookies. It must be called before any HTML is sent.
   // Upon success with a 'set' or 'delete' the plug-in returns
   // TRUE. For a successful 'read' it returns the read value.
   // On failure it returns FALSE. It requires the following
   // arguments:
   //
   //    $action: If 'set' then set $cookie to $value
   //             If 'read' return the value of $cookie
   //             If 'delete' delete $cookie
   //    $cookie: Name of a cookie to set/read/delete
   //    $value:  If setting a cookie use this value: any string
   //    $expire: If setting a cookie use this value: number
   //             of seconds before cookie expires, or use
   //             NULL to let cookie expire at browser session
   //             end
   //    $path:   The path to the cookie on the server:
   //             Generally this will be '/'

   switch(strtolower($action))
   {
      case 'set':
         if ($expire) $expire += time();
         return setcookie($cookie, $value, $expire, $path);

      case 'read':
         if (isset($_COOKIE[$cookie]))
            return $_COOKIE[$cookie];
         else return FALSE;

      case 'delete':
         if (isset($_COOKIE[$cookie]))
            return setcookie($cookie, NULL,
               time() - 60 * 60 * 24 * 30, NULL);
         else return FALSE;
   }
   
   return FALSE;
}

?>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章