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

PHP模拟asp中response类实现方法

程序员文章站 2022-07-21 21:17:42
本文实例讲述了php模拟asp中response类的方法。分享给大家供大家参考。具体如下: 习惯了asp或是asp.net开发的人, 他们会经常用到response类,这...

本文实例讲述了php模拟asp中response类的方法。分享给大家供大家参考。具体如下:

习惯了asp或是asp.net开发的人, 他们会经常用到response类,这个类用于处理客户端的响应,可以实现跳转,输出等功能. 在php中没有这个类,但是确实可以通过函数来模拟这个类.

/* 
* 类用途: 实现类似于asp中的response功能 
*/
final class response { 
  private $headers = array();  
  private $output; 
  private $level = 0; 
  public function addheader($key, $value) { 
    $this->headers[$key] = $value; 
  } 
  public function removeheader($key) { 
    if (isset($this->headers[$key])) { 
      unset($this->headers[$key]); 
    } 
  } 
  public function redirect($url) { 
    header('location: ' . $url); 
    exit; 
  } 
  public function setoutput($output, $level = 0) { 
    $this->output = $output; 
    $this->level = $level; 
  } 
  private function compress($data, $level = 0) { 
    if (isset($_server['http_accept_encoding']) && (strpos($_server['http_accept_encoding'], 'gzip') !== false)) { 
      $encoding = 'gzip'; 
    }  
    if (isset($_server['http_accept_encoding']) && (strpos($_server['http_accept_encoding'], 'x-gzip') !== false)) { 
      $encoding = 'x-gzip'; 
    } 
    if (!isset($encoding)) { 
      return $data; 
    } 
    if (!extension_loaded('zlib') || ini_get('zlib.output_compression')) { 
      return $data; 
    } 
    if (headers_sent()) { 
      return $data; 
    } 
    if (connection_status()) {  
      return $data; 
    } 
    $this->addheader('content-encoding', $encoding); 
    return gzencode($data, (int)$level); 
  } 
  public function output() { 
    if ($this->level) { 
      $ouput = $this->compress($this->output, $this->level); 
    } else { 
      $ouput = $this->output; 
    }   
    if (!headers_sent()) { 
      foreach ($this->headers as $key => $value) { 
        header($key . ': ' . $value); 
      } 
    } 
    echo $ouput; 
  } 
}

希望本文所述对大家的php程序设计有所帮助。