Request.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. <?php
  2. /**
  3. * Slim - a micro PHP 5 framework
  4. *
  5. * @author Josh Lockhart <[email protected]>
  6. * @copyright 2011 Josh Lockhart
  7. * @link http://www.slimframework.com
  8. * @license http://www.slimframework.com/license
  9. * @version 2.2.0
  10. * @package Slim
  11. *
  12. * MIT LICENSE
  13. *
  14. * Permission is hereby granted, free of charge, to any person obtaining
  15. * a copy of this software and associated documentation files (the
  16. * "Software"), to deal in the Software without restriction, including
  17. * without limitation the rights to use, copy, modify, merge, publish,
  18. * distribute, sublicense, and/or sell copies of the Software, and to
  19. * permit persons to whom the Software is furnished to do so, subject to
  20. * the following conditions:
  21. *
  22. * The above copyright notice and this permission notice shall be
  23. * included in all copies or substantial portions of the Software.
  24. *
  25. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  28. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  29. * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  30. * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. */
  33. namespace Slim\Http;
  34. /**
  35. * Slim HTTP Request
  36. *
  37. * This class provides a human-friendly interface to the Slim environment variables;
  38. * environment variables are passed by reference and will be modified directly.
  39. *
  40. * @package Slim
  41. * @author Josh Lockhart
  42. * @since 1.0.0
  43. */
  44. class Request
  45. {
  46. const METHOD_HEAD = 'HEAD';
  47. const METHOD_GET = 'GET';
  48. const METHOD_POST = 'POST';
  49. const METHOD_PUT = 'PUT';
  50. const METHOD_DELETE = 'DELETE';
  51. const METHOD_OPTIONS = 'OPTIONS';
  52. const METHOD_OVERRIDE = '_METHOD';
  53. /**
  54. * @var array
  55. */
  56. protected static $formDataMediaTypes = array('application/x-www-form-urlencoded');
  57. /**
  58. * @var array
  59. */
  60. protected $env;
  61. /**
  62. * Constructor
  63. * @param array $env
  64. * @see \Slim\Environment
  65. */
  66. public function __construct($env)
  67. {
  68. $this->env = $env;
  69. }
  70. /**
  71. * Get HTTP method
  72. * @return string
  73. */
  74. public function getMethod()
  75. {
  76. return $this->env['REQUEST_METHOD'];
  77. }
  78. /**
  79. * Is this a GET request?
  80. * @return bool
  81. */
  82. public function isGet()
  83. {
  84. return $this->getMethod() === self::METHOD_GET;
  85. }
  86. /**
  87. * Is this a POST request?
  88. * @return bool
  89. */
  90. public function isPost()
  91. {
  92. return $this->getMethod() === self::METHOD_POST;
  93. }
  94. /**
  95. * Is this a PUT request?
  96. * @return bool
  97. */
  98. public function isPut()
  99. {
  100. return $this->getMethod() === self::METHOD_PUT;
  101. }
  102. /**
  103. * Is this a DELETE request?
  104. * @return bool
  105. */
  106. public function isDelete()
  107. {
  108. return $this->getMethod() === self::METHOD_DELETE;
  109. }
  110. /**
  111. * Is this a HEAD request?
  112. * @return bool
  113. */
  114. public function isHead()
  115. {
  116. return $this->getMethod() === self::METHOD_HEAD;
  117. }
  118. /**
  119. * Is this a OPTIONS request?
  120. * @return bool
  121. */
  122. public function isOptions()
  123. {
  124. return $this->getMethod() === self::METHOD_OPTIONS;
  125. }
  126. /**
  127. * Is this an AJAX request?
  128. * @return bool
  129. */
  130. public function isAjax()
  131. {
  132. if ($this->params('isajax')) {
  133. return true;
  134. } elseif (isset($this->env['X_REQUESTED_WITH']) && $this->env['X_REQUESTED_WITH'] === 'XMLHttpRequest') {
  135. return true;
  136. } else {
  137. return false;
  138. }
  139. }
  140. /**
  141. * Is this an XHR request? (alias of Slim_Http_Request::isAjax)
  142. * @return bool
  143. */
  144. public function isXhr()
  145. {
  146. return $this->isAjax();
  147. }
  148. /**
  149. * Fetch GET and POST data
  150. *
  151. * This method returns a union of GET and POST data as a key-value array, or the value
  152. * of the array key if requested; if the array key does not exist, NULL is returned.
  153. *
  154. * @param string $key
  155. * @return array|mixed|null
  156. */
  157. public function params($key = null)
  158. {
  159. $union = array_merge($this->get(), $this->post());
  160. if ($key) {
  161. if (isset($union[$key])) {
  162. return $union[$key];
  163. } else {
  164. return null;
  165. }
  166. } else {
  167. return $union;
  168. }
  169. }
  170. /**
  171. * Fetch GET data
  172. *
  173. * This method returns a key-value array of data sent in the HTTP request query string, or
  174. * the value of the array key if requested; if the array key does not exist, NULL is returned.
  175. *
  176. * @param string $key
  177. * @return array|mixed|null
  178. */
  179. public function get($key = null)
  180. {
  181. if (!isset($this->env['slim.request.query_hash'])) {
  182. $output = array();
  183. if (function_exists('mb_parse_str') && !isset($this->env['slim.tests.ignore_multibyte'])) {
  184. mb_parse_str($this->env['QUERY_STRING'], $output);
  185. } else {
  186. parse_str($this->env['QUERY_STRING'], $output);
  187. }
  188. $this->env['slim.request.query_hash'] = Util::stripSlashesIfMagicQuotes($output);
  189. }
  190. if ($key) {
  191. if (isset($this->env['slim.request.query_hash'][$key])) {
  192. return $this->env['slim.request.query_hash'][$key];
  193. } else {
  194. return null;
  195. }
  196. } else {
  197. return $this->env['slim.request.query_hash'];
  198. }
  199. }
  200. /**
  201. * Fetch POST data
  202. *
  203. * This method returns a key-value array of data sent in the HTTP request body, or
  204. * the value of a hash key if requested; if the array key does not exist, NULL is returned.
  205. *
  206. * @param string $key
  207. * @return array|mixed|null
  208. * @throws \RuntimeException If environment input is not available
  209. */
  210. public function post($key = null)
  211. {
  212. if (!isset($this->env['slim.input'])) {
  213. throw new \RuntimeException('Missing slim.input in environment variables');
  214. }
  215. if (!isset($this->env['slim.request.form_hash'])) {
  216. $this->env['slim.request.form_hash'] = array();
  217. if ($this->isFormData() && is_string($this->env['slim.input'])) {
  218. $output = array();
  219. if (function_exists('mb_parse_str') && !isset($this->env['slim.tests.ignore_multibyte'])) {
  220. mb_parse_str($this->env['slim.input'], $output);
  221. } else {
  222. parse_str($this->env['slim.input'], $output);
  223. }
  224. $this->env['slim.request.form_hash'] = Util::stripSlashesIfMagicQuotes($output);
  225. } else {
  226. $this->env['slim.request.form_hash'] = Util::stripSlashesIfMagicQuotes($_POST);
  227. }
  228. }
  229. if ($key) {
  230. if (isset($this->env['slim.request.form_hash'][$key])) {
  231. return $this->env['slim.request.form_hash'][$key];
  232. } else {
  233. return null;
  234. }
  235. } else {
  236. return $this->env['slim.request.form_hash'];
  237. }
  238. }
  239. /**
  240. * Fetch PUT data (alias for \Slim\Http\Request::post)
  241. * @param string $key
  242. * @return array|mixed|null
  243. */
  244. public function put($key = null)
  245. {
  246. return $this->post($key);
  247. }
  248. /**
  249. * Fetch DELETE data (alias for \Slim\Http\Request::post)
  250. * @param string $key
  251. * @return array|mixed|null
  252. */
  253. public function delete($key = null)
  254. {
  255. return $this->post($key);
  256. }
  257. /**
  258. * Fetch COOKIE data
  259. *
  260. * This method returns a key-value array of Cookie data sent in the HTTP request, or
  261. * the value of a array key if requested; if the array key does not exist, NULL is returned.
  262. *
  263. * @param string $key
  264. * @return array|string|null
  265. */
  266. public function cookies($key = null)
  267. {
  268. if (!isset($this->env['slim.request.cookie_hash'])) {
  269. $cookieHeader = isset($this->env['COOKIE']) ? $this->env['COOKIE'] : '';
  270. $this->env['slim.request.cookie_hash'] = Util::parseCookieHeader($cookieHeader);
  271. }
  272. if ($key) {
  273. if (isset($this->env['slim.request.cookie_hash'][$key])) {
  274. return $this->env['slim.request.cookie_hash'][$key];
  275. } else {
  276. return null;
  277. }
  278. } else {
  279. return $this->env['slim.request.cookie_hash'];
  280. }
  281. }
  282. /**
  283. * Does the Request body contain parseable form data?
  284. * @return bool
  285. */
  286. public function isFormData()
  287. {
  288. $method = isset($this->env['slim.method_override.original_method']) ? $this->env['slim.method_override.original_method'] : $this->getMethod();
  289. return ($method === self::METHOD_POST && is_null($this->getContentType())) || in_array($this->getMediaType(), self::$formDataMediaTypes);
  290. }
  291. /**
  292. * Get Headers
  293. *
  294. * This method returns a key-value array of headers sent in the HTTP request, or
  295. * the value of a hash key if requested; if the array key does not exist, NULL is returned.
  296. *
  297. * @param string $key
  298. * @param mixed $default The default value returned if the requested header is not available
  299. * @return mixed
  300. */
  301. public function headers($key = null, $default = null)
  302. {
  303. if ($key) {
  304. $key = strtoupper($key);
  305. $key = str_replace('-', '_', $key);
  306. $key = preg_replace('@^HTTP_@', '', $key);
  307. if (isset($this->env[$key])) {
  308. return $this->env[$key];
  309. } else {
  310. return $default;
  311. }
  312. } else {
  313. $headers = array();
  314. foreach ($this->env as $key => $value) {
  315. if (strpos($key, 'slim.') !== 0) {
  316. $headers[$key] = $value;
  317. }
  318. }
  319. return $headers;
  320. }
  321. }
  322. /**
  323. * Get Body
  324. * @return string
  325. */
  326. public function getBody()
  327. {
  328. return $this->env['slim.input'];
  329. }
  330. /**
  331. * Get Content Type
  332. * @return string
  333. */
  334. public function getContentType()
  335. {
  336. if (isset($this->env['CONTENT_TYPE'])) {
  337. return $this->env['CONTENT_TYPE'];
  338. } else {
  339. return null;
  340. }
  341. }
  342. /**
  343. * Get Media Type (type/subtype within Content Type header)
  344. * @return string|null
  345. */
  346. public function getMediaType()
  347. {
  348. $contentType = $this->getContentType();
  349. if ($contentType) {
  350. $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType);
  351. return strtolower($contentTypeParts[0]);
  352. } else {
  353. return null;
  354. }
  355. }
  356. /**
  357. * Get Media Type Params
  358. * @return array
  359. */
  360. public function getMediaTypeParams()
  361. {
  362. $contentType = $this->getContentType();
  363. $contentTypeParams = array();
  364. if ($contentType) {
  365. $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType);
  366. $contentTypePartsLength = count($contentTypeParts);
  367. for ($i = 1; $i < $contentTypePartsLength; $i++) {
  368. $paramParts = explode('=', $contentTypeParts[$i]);
  369. $contentTypeParams[strtolower($paramParts[0])] = $paramParts[1];
  370. }
  371. }
  372. return $contentTypeParams;
  373. }
  374. /**
  375. * Get Content Charset
  376. * @return string|null
  377. */
  378. public function getContentCharset()
  379. {
  380. $mediaTypeParams = $this->getMediaTypeParams();
  381. if (isset($mediaTypeParams['charset'])) {
  382. return $mediaTypeParams['charset'];
  383. } else {
  384. return null;
  385. }
  386. }
  387. /**
  388. * Get Content-Length
  389. * @return int
  390. */
  391. public function getContentLength()
  392. {
  393. if (isset($this->env['CONTENT_LENGTH'])) {
  394. return (int) $this->env['CONTENT_LENGTH'];
  395. } else {
  396. return 0;
  397. }
  398. }
  399. /**
  400. * Get Host
  401. * @return string
  402. */
  403. public function getHost()
  404. {
  405. if (isset($this->env['HOST'])) {
  406. if (strpos($this->env['HOST'], ':') !== false) {
  407. $hostParts = explode(':', $this->env['HOST']);
  408. return $hostParts[0];
  409. }
  410. return $this->env['HOST'];
  411. } else {
  412. return $this->env['SERVER_NAME'];
  413. }
  414. }
  415. /**
  416. * Get Host with Port
  417. * @return string
  418. */
  419. public function getHostWithPort()
  420. {
  421. return sprintf('%s:%s', $this->getHost(), $this->getPort());
  422. }
  423. /**
  424. * Get Port
  425. * @return int
  426. */
  427. public function getPort()
  428. {
  429. return (int) $this->env['SERVER_PORT'];
  430. }
  431. /**
  432. * Get Scheme (https or http)
  433. * @return string
  434. */
  435. public function getScheme()
  436. {
  437. return $this->env['slim.url_scheme'];
  438. }
  439. /**
  440. * Get Script Name (physical path)
  441. * @return string
  442. */
  443. public function getScriptName()
  444. {
  445. return $this->env['SCRIPT_NAME'];
  446. }
  447. /**
  448. * LEGACY: Get Root URI (alias for Slim_Http_Request::getScriptName)
  449. * @return string
  450. */
  451. public function getRootUri()
  452. {
  453. return $this->getScriptName();
  454. }
  455. /**
  456. * Get Path (physical path + virtual path)
  457. * @return string
  458. */
  459. public function getPath()
  460. {
  461. return $this->getScriptName() . $this->getPathInfo();
  462. }
  463. /**
  464. * Get Path Info (virtual path)
  465. * @return string
  466. */
  467. public function getPathInfo()
  468. {
  469. return $this->env['PATH_INFO'];
  470. }
  471. /**
  472. * LEGACY: Get Resource URI (alias for Slim_Http_Request::getPathInfo)
  473. * @return string
  474. */
  475. public function getResourceUri()
  476. {
  477. return $this->getPathInfo();
  478. }
  479. /**
  480. * Get URL (scheme + host [ + port if non-standard ])
  481. * @return string
  482. */
  483. public function getUrl()
  484. {
  485. $url = $this->getScheme() . '://' . $this->getHost();
  486. if (($this->getScheme() === 'https' && $this->getPort() !== 443) || ($this->getScheme() === 'http' && $this->getPort() !== 80)) {
  487. $url .= sprintf(':%s', $this->getPort());
  488. }
  489. return $url;
  490. }
  491. /**
  492. * Get IP
  493. * @return string
  494. */
  495. public function getIp()
  496. {
  497. if (isset($this->env['X_FORWARDED_FOR'])) {
  498. return $this->env['X_FORWARDED_FOR'];
  499. } elseif (isset($this->env['CLIENT_IP'])) {
  500. return $this->env['CLIENT_IP'];
  501. }
  502. return $this->env['REMOTE_ADDR'];
  503. }
  504. /**
  505. * Get Referrer
  506. * @return string|null
  507. */
  508. public function getReferrer()
  509. {
  510. if (isset($this->env['REFERER'])) {
  511. return $this->env['REFERER'];
  512. } else {
  513. return null;
  514. }
  515. }
  516. /**
  517. * Get Referer (for those who can't spell)
  518. * @return string|null
  519. */
  520. public function getReferer()
  521. {
  522. return $this->getReferrer();
  523. }
  524. /**
  525. * Get User Agent
  526. * @return string|null
  527. */
  528. public function getUserAgent()
  529. {
  530. if (isset($this->env['USER_AGENT'])) {
  531. return $this->env['USER_AGENT'];
  532. } else {
  533. return null;
  534. }
  535. }
  536. }