HeaderTrait.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. <?php
  2. /**
  3. * A parallel HTTP client written in pure PHP
  4. *
  5. * @author hightman <hightman@twomice.net>
  6. * @link http://hightman.cn
  7. * @copyright Copyright (c) 2015 Twomice Studio.
  8. */
  9. namespace hightman\http;
  10. /**
  11. * Http base operations
  12. * Handle cookie and other headers.
  13. *
  14. * @author hightman
  15. * @since 1.0
  16. */
  17. trait HeaderTrait
  18. {
  19. protected $_headers = [];
  20. protected $_cookies = [];
  21. /**
  22. * Set http header or headers
  23. * @param mixed $key string key or key-value pairs to set multiple headers.
  24. * @param string $value the header value when key is string, set null to remove header.
  25. */
  26. public function setHeader($key, $value = null)
  27. {
  28. if (is_array($key)) {
  29. foreach ($key as $k => $v) {
  30. $this->setHeader($k, $v);
  31. }
  32. } else {
  33. $key = strtolower($key);
  34. if ($value === null) {
  35. unset($this->_headers[$key]);
  36. } else {
  37. $this->_headers[$key] = $value;
  38. }
  39. }
  40. }
  41. /**
  42. * Add http header or headers
  43. * @param mixed $key string key or key-value pairs to be added.
  44. * @param string $value the header value when key is string.
  45. */
  46. public function addHeader($key, $value = null)
  47. {
  48. if (is_array($key)) {
  49. foreach ($key as $k => $v) {
  50. $this->addHeader($k, $v);
  51. }
  52. } else {
  53. if ($value !== null) {
  54. $key = strtolower($key);
  55. if (!isset($this->_headers[$key])) {
  56. $this->_headers[$key] = $value;
  57. } else {
  58. if (is_array($this->_headers[$key])) {
  59. $this->_headers[$key][] = $value;
  60. } else {
  61. $this->_headers[$key] = [$this->_headers[$key], $value];
  62. }
  63. }
  64. }
  65. }
  66. }
  67. /**
  68. * Clean http header
  69. */
  70. public function clearHeader()
  71. {
  72. $this->_headers = [];
  73. }
  74. /**
  75. * Get a http header or all http headers
  76. * @param mixed $key the header key to be got, or null to get all headers
  77. * @return array|string the header value, or headers array when key is null.
  78. */
  79. public function getHeader($key = null)
  80. {
  81. if ($key === null) {
  82. return $this->_headers;
  83. }
  84. $key = strtolower($key);
  85. return isset($this->_headers[$key]) ? $this->_headers[$key] : null;
  86. }
  87. /**
  88. * Check HTTP header is set or not
  89. * @param string $key the header key to be check, not case sensitive
  90. * @return boolean if there is http header with the name.
  91. */
  92. public function hasHeader($key)
  93. {
  94. return isset($this->_headers[strtolower($key)]);
  95. }
  96. /**
  97. * Set a raw cookie
  98. * @param string $key cookie name
  99. * @param string $value cookie value
  100. * @param integer $expires cookie will be expired after this timestamp.
  101. * @param string $domain cookie domain
  102. * @param string $path cookie path
  103. */
  104. public function setRawCookie($key, $value, $expires = null, $domain = '-', $path = '/')
  105. {
  106. $domain = strtolower($domain);
  107. if (substr($domain, 0, 1) === '.') {
  108. $domain = substr($domain, 1);
  109. }
  110. if (!isset($this->_cookies[$domain])) {
  111. $this->_cookies[$domain] = [];
  112. }
  113. if (!isset($this->_cookies[$domain][$path])) {
  114. $this->_cookies[$domain][$path] = [];
  115. }
  116. $list = &$this->_cookies[$domain][$path];
  117. if ($value === null || $value === '' || ($expires !== null && $expires < time())) {
  118. unset($list[$key]);
  119. } else {
  120. $list[$key] = ['value' => $value, 'expires' => $expires];
  121. }
  122. }
  123. /**
  124. * Set a normal cookie
  125. * @param string $key cookie name
  126. * @param string $value cookie value
  127. */
  128. public function setCookie($key, $value)
  129. {
  130. $this->setRawCookie($key, rawurlencode($value));
  131. }
  132. /**
  133. * Clean all cookies
  134. * @param string $domain use null to clean all cookies, '-' to clean current cookies.
  135. * @param string $path
  136. */
  137. public function clearCookie($domain = '-', $path = null)
  138. {
  139. if ($domain === null) {
  140. $this->_cookies = [];
  141. } else {
  142. $domain = strtolower($domain);
  143. if ($path === null) {
  144. unset($this->_cookies[$domain]);
  145. } else {
  146. if (isset($this->_cookies[$domain])) {
  147. unset($this->_cookies[$domain][$path]);
  148. }
  149. }
  150. }
  151. }
  152. /**
  153. * Get cookie value
  154. * @param string $key passing null to get all cookies
  155. * @param string $domain passing '-' to fetch from current session,
  156. * @return array|null|string
  157. */
  158. public function getCookie($key, $domain = '-')
  159. {
  160. $domain = strtolower($domain);
  161. if ($key === null) {
  162. $cookies = [];
  163. }
  164. while (true) {
  165. if (isset($this->_cookies[$domain])) {
  166. foreach ($this->_cookies[$domain] as $path => $list) {
  167. if ($key === null) {
  168. $cookies = array_merge($list, $cookies);
  169. } else {
  170. if (isset($list[$key])) {
  171. return rawurldecode($list[$key]['value']);
  172. }
  173. }
  174. }
  175. }
  176. if (($pos = strpos($domain, '.', 1)) === false) {
  177. break;
  178. }
  179. $domain = substr($domain, $pos);
  180. }
  181. return $key === null ? $cookies : null;
  182. }
  183. /**
  184. * Apply cookies for request
  185. * @param Request $req
  186. */
  187. public function applyCookie($req)
  188. {
  189. // fetch cookies
  190. $host = $req->getHeader('host');
  191. $path = $req->getUrlParam('path');
  192. $cookies = $this->fetchCookieToSend($host, $path);
  193. if ($this !== $req) {
  194. $cookies = array_merge($cookies, $req->fetchCookieToSend($host, $path));
  195. }
  196. // add to header
  197. $req->setHeader('cookie', null);
  198. foreach (array_chunk(array_values($cookies), 3) as $chunk) {
  199. $req->addHeader('cookie', implode('; ', $chunk));
  200. }
  201. }
  202. /**
  203. * Fetch cookies to be sent
  204. * @param string $host
  205. * @param string $path
  206. * @return array
  207. */
  208. public function fetchCookieToSend($host, $path)
  209. {
  210. $now = time();
  211. $host = strtolower($host);
  212. $cookies = [];
  213. $domains = ['-', $host];
  214. while (strlen($host) > 1 && ($pos = strpos($host, '.', 1)) !== false) {
  215. $host = substr($host, $pos + 1);
  216. $domains[] = $host;
  217. }
  218. foreach ($domains as $domain) {
  219. if (!isset($this->_cookies[$domain])) {
  220. continue;
  221. }
  222. foreach ($this->_cookies[$domain] as $_path => $list) {
  223. if (!strncmp($_path, $path, strlen($_path))
  224. && (substr($_path, -1, 1) === '/' || substr($path, strlen($_path), 1) === '/')
  225. ) {
  226. foreach ($list as $k => $v) {
  227. if (!isset($cookies[$k]) && ($v['expires'] === null || $v['expires'] > $now)) {
  228. $cookies[$k] = $k . '=' . $v['value'];
  229. }
  230. }
  231. }
  232. }
  233. }
  234. return $cookies;
  235. }
  236. protected function fetchCookieToSave()
  237. {
  238. $now = time();
  239. $cookies = [];
  240. foreach ($this->_cookies as $domain => $_list1) {
  241. $list1 = [];
  242. foreach ($_list1 as $path => $_list2) {
  243. $list2 = [];
  244. foreach ($_list2 as $k => $v) {
  245. if ($v['expires'] === null || $v['expires'] < $now) {
  246. continue;
  247. }
  248. $list2[$k] = $v;
  249. }
  250. if (count($list2) > 0) {
  251. $list1[$path] = $list2;
  252. }
  253. }
  254. if (count($list1) > 0) {
  255. $cookies[$domain] = $list1;
  256. }
  257. }
  258. return $cookies;
  259. }
  260. protected function loadCookie($file)
  261. {
  262. if (file_exists($file)) {
  263. $this->_cookies = unserialize(file_get_contents($file));
  264. }
  265. }
  266. protected function saveCookie($file)
  267. {
  268. file_put_contents($file, serialize($this->fetchCookieToSave()));
  269. }
  270. }