当前位置:Gxlcms > PHP教程 > PHP模拟asp中response类实现方法_php技巧

PHP模拟asp中response类实现方法_php技巧

时间:2021-07-01 10:21:17 帮助过:15人阅读

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

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

  1. /*
  2. * 类用途: 实现类似于asp中的response功能
  3. */
  4. final class Response {
  5. private $headers = array();
  6. private $output;
  7. private $level = 0;
  8. public function addHeader($key, $value) {
  9. $this->headers[$key] = $value;
  10. }
  11. public function removeHeader($key) {
  12. if (isset($this->headers[$key])) {
  13. unset($this->headers[$key]);
  14. }
  15. }
  16. public function redirect($url) {
  17. header('Location: ' . $url);
  18. exit;
  19. }
  20. public function setOutput($output, $level = 0) {
  21. $this->output = $output;
  22. $this->level = $level;
  23. }
  24. private function compress($data, $level = 0) {
  25. if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE)) {
  26. $encoding = 'gzip';
  27. }
  28. if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip') !== FALSE)) {
  29. $encoding = 'x-gzip';
  30. }
  31. if (!isset($encoding)) {
  32. return $data;
  33. }
  34. if (!extension_loaded('zlib') || ini_get('zlib.output_compression')) {
  35. return $data;
  36. }
  37. if (headers_sent()) {
  38. return $data;
  39. }
  40. if (connection_status()) {
  41. return $data;
  42. }
  43. $this->addHeader('Content-Encoding', $encoding);
  44. return gzencode($data, (int)$level);
  45. }
  46. public function output() {
  47. if ($this->level) {
  48. $ouput = $this->compress($this->output, $this->level);
  49. } else {
  50. $ouput = $this->output;
  51. }
  52. if (!headers_sent()) {
  53. foreach ($this->headers as $key => $value) {
  54. header($key . ': ' . $value);
  55. }
  56. }
  57. echo $ouput;
  58. }
  59. }

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

人气教程排行