這篇文章主要介紹了PHP模擬asp中response類的方法,可實現模擬ASP中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程序設計有所幫助。
|
新聞熱點
疑難解答