1. <?php
  2. /**
  3.  * 用于rpc服务端的header系列函数
  4.  * @author flynetcn
  5.  */
  6. class Utils_Header
  7. {
  8.     private static $headers = array();
  9.     private static $cookies = array();
  10.     private static $sessionOpened = false;

  11.     public static function header($string, $replace=true, $http_response_code=null)
  12.     {
  13.         if (PHP_SAPI == 'cli') {
  14.             if ($http_response_code) {
  15.                 self::$headers[] = array($string, $replace, $http_response_code);
  16.             } else {
  17.                 self::$headers[] = array($string, $replace);
  18.             }
  19.         }
  20.         if ($http_response_code) {
  21.             header($string, $replace, $http_response_code);
  22.         } else {
  23.             header($string, $replace);
  24.         }
  25.     }

  26.     public static function session_start()
  27.     {
  28.         if (PHP_SAPI == 'cli' && !self::$sessionOpened) {
  29.             //模拟session机制
  30.             if (!$_COOKIE[session_name()]) {
  31.                 $ip_prefix = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? ip2long($_SERVER['HTTP_X_FORWARDED_FOR']) : rand(1, 10000);
  32.                 $pid_prefix = posix_getpid();
  33.                 $sessid = uniqid(strval(dechex($ip_prefix)).strval(dechex($pid_prefix)));
  34.                 $_COOKIE[session_name()] = $sessid;
  35.                 session_start();
  36.                 self::$cookies[] = array(session_name(), $sessid, 0, '/', DOMAIN_COOKIE);
  37.             } else {
  38.                 session_start();
  39.             }
  40.             self::$sessionOpened = true;
  41.             return true;
  42.         } else {
  43.             return session_start();
  44.         }
  45.     }

  46.     public static function session_write_close()
  47.     {
  48.         if (self::$sessionOpened) {
  49.             self::$sessionOpened = false;
  50.         }
  51.         $_SESSION = array();
  52.         session_write_close();
  53.     }

  54.     public static function setcookie($name, $value='', $expire=0, $path='', $domain='', $secure=false, $httponly=false)
  55.     {
  56.         if (PHP_SAPI == 'cli') {
  57.             self::$cookies[] = func_get_args();
  58.         }
  59.         return call_user_func_array('setcookie', func_get_args());
  60.     }

  61.     public static function getSendCookies()
  62.     {
  63.         return self::$cookies;
  64.     }

  65.     public static function getSendHeaders()
  66.     {
  67.         return self::$headers;
  68.     }

  69.     public static function cleanSendCookies()
  70.     {
  71.         self::$cookies = array();
  72.     }

  73.     public static function cleanSendHeaders()
  74.     {
  75.         self::$headers = array();
  76.     }
  77. }

12-25 01:55