Http.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace Qii\Response;
  3. class Http extends \Qii\Base\Response
  4. {
  5. protected $_sendheader = true;
  6. protected $_responseCode = 200;
  7. /**
  8. * Set HTTP response code to use with headers
  9. *
  10. * @param int $code
  11. * @return Qii\Response\Http
  12. */
  13. public function setResponseCode($code)
  14. {
  15. if (!is_int($code) || (100 > $code) || (599 < $code)) {
  16. throw new \Qii\Exceptions\Response('Invalid HTTP response code');
  17. }
  18. $this->_responseCode = $code;
  19. return $this;
  20. }
  21. /**
  22. * Retrieve HTTP response code
  23. *
  24. * @return int
  25. */
  26. public function getResponseCode()
  27. {
  28. return $this->_responseCode;
  29. }
  30. /**
  31. * Send all headers
  32. *
  33. * Sends any headers specified.
  34. * If an {@link setResponseCode() HTTP response code}
  35. * has been specified, it is sent with the first header.
  36. *
  37. * @return Qii_Response_Http
  38. */
  39. protected function sendHeaders()
  40. {
  41. $httpCodeSent = false;
  42. if (!$this->_sendheader) {
  43. return $this;
  44. }
  45. foreach ($this->_headers as $header) {
  46. if (!$httpCodeSent && $this->_responseCode) {
  47. header(
  48. $header['name'] . ': ' . $header['value'],
  49. $header['replace'], $this->_responseCode
  50. );
  51. $httpCodeSent = true;
  52. } else {
  53. header(
  54. $header['name'] . ': ' . $header['value'],
  55. $header['replace']
  56. );
  57. }
  58. }
  59. return $this;
  60. }
  61. /**
  62. * Set redirect URL
  63. *
  64. * Sets Location header. Forces replacement of any prior redirects.
  65. *
  66. * @param string $url
  67. * @return Qii_Response_Abstract
  68. */
  69. public function setRedirect($url)
  70. {
  71. $this->setHeader('Location', $url, true)
  72. ->setResponseCode(302);
  73. return $this;
  74. }
  75. }