CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.10 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.10
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper
  • None

Classes

  • CakeRequest
  • CakeResponse
  • CakeSocket
   1: <?php
   2: /**
   3:  * CakeRequest
   4:  *
   5:  * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
   6:  * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
   7:  *
   8:  * Licensed under The MIT License
   9:  * For full copyright and license information, please see the LICENSE.txt
  10:  * Redistributions of files must retain the above copyright notice.
  11:  *
  12:  * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  13:  * @link          https://cakephp.org CakePHP(tm) Project
  14:  * @since         CakePHP(tm) v 2.0
  15:  * @license       https://opensource.org/licenses/mit-license.php MIT License
  16:  */
  17: 
  18: App::uses('Hash', 'Utility');
  19: 
  20: /**
  21:  * A class that helps wrap Request information and particulars about a single request.
  22:  * Provides methods commonly used to introspect on the request headers and request body.
  23:  *
  24:  * Has both an Array and Object interface. You can access framework parameters using indexes:
  25:  *
  26:  * `$request['controller']` or `$request->controller`.
  27:  *
  28:  * @property string $plugin     The plugin handling the request. Will be `null` when there is no plugin.
  29:  * @property string $controller The controller handling the current request.
  30:  * @property string $action     The action handling the current request.
  31:  * @property array $named       Array of named parameters parsed from the URL.
  32:  * @property array $pass        Array of passed arguments parsed from the URL.
  33:  * @package       Cake.Network
  34:  */
  35: class CakeRequest implements ArrayAccess {
  36: 
  37: /**
  38:  * Array of parameters parsed from the URL.
  39:  *
  40:  * @var array
  41:  */
  42:     public $params = array(
  43:         'plugin' => null,
  44:         'controller' => null,
  45:         'action' => null,
  46:         'named' => array(),
  47:         'pass' => array(),
  48:     );
  49: 
  50: /**
  51:  * Array of POST data. Will contain form data as well as uploaded files.
  52:  * Inputs prefixed with 'data' will have the data prefix removed. If there is
  53:  * overlap between an input prefixed with data and one without, the 'data' prefixed
  54:  * value will take precedence.
  55:  *
  56:  * @var array
  57:  */
  58:     public $data = array();
  59: 
  60: /**
  61:  * Array of querystring arguments
  62:  *
  63:  * @var array
  64:  */
  65:     public $query = array();
  66: 
  67: /**
  68:  * The URL string used for the request.
  69:  *
  70:  * @var string
  71:  */
  72:     public $url;
  73: 
  74: /**
  75:  * Base URL path.
  76:  *
  77:  * @var string
  78:  */
  79:     public $base = false;
  80: 
  81: /**
  82:  * webroot path segment for the request.
  83:  *
  84:  * @var string
  85:  */
  86:     public $webroot = '/';
  87: 
  88: /**
  89:  * The full address to the current request
  90:  *
  91:  * @var string
  92:  */
  93:     public $here = null;
  94: 
  95: /**
  96:  * The built in detectors used with `is()` can be modified with `addDetector()`.
  97:  *
  98:  * There are several ways to specify a detector, see CakeRequest::addDetector() for the
  99:  * various formats and ways to define detectors.
 100:  *
 101:  * @var array
 102:  */
 103:     protected $_detectors = array(
 104:         'get' => array('env' => 'REQUEST_METHOD', 'value' => 'GET'),
 105:         'patch' => array('env' => 'REQUEST_METHOD', 'value' => 'PATCH'),
 106:         'post' => array('env' => 'REQUEST_METHOD', 'value' => 'POST'),
 107:         'put' => array('env' => 'REQUEST_METHOD', 'value' => 'PUT'),
 108:         'delete' => array('env' => 'REQUEST_METHOD', 'value' => 'DELETE'),
 109:         'head' => array('env' => 'REQUEST_METHOD', 'value' => 'HEAD'),
 110:         'options' => array('env' => 'REQUEST_METHOD', 'value' => 'OPTIONS'),
 111:         'ssl' => array('env' => 'HTTPS', 'value' => 1),
 112:         'ajax' => array('env' => 'HTTP_X_REQUESTED_WITH', 'value' => 'XMLHttpRequest'),
 113:         'flash' => array('env' => 'HTTP_USER_AGENT', 'pattern' => '/^(Shockwave|Adobe) Flash/'),
 114:         'mobile' => array('env' => 'HTTP_USER_AGENT', 'options' => array(
 115:             'Android', 'AvantGo', 'BB10', 'BlackBerry', 'DoCoMo', 'Fennec', 'iPod', 'iPhone', 'iPad',
 116:             'J2ME', 'MIDP', 'NetFront', 'Nokia', 'Opera Mini', 'Opera Mobi', 'PalmOS', 'PalmSource',
 117:             'portalmmm', 'Plucker', 'ReqwirelessWeb', 'SonyEricsson', 'Symbian', 'UP\\.Browser',
 118:             'webOS', 'Windows CE', 'Windows Phone OS', 'Xiino'
 119:         )),
 120:         'requested' => array('param' => 'requested', 'value' => 1),
 121:         'json' => array('accept' => array('application/json'), 'param' => 'ext', 'value' => 'json'),
 122:         'xml' => array('accept' => array('application/xml', 'text/xml'), 'param' => 'ext', 'value' => 'xml'),
 123:     );
 124: 
 125: /**
 126:  * Copy of php://input. Since this stream can only be read once in most SAPI's
 127:  * keep a copy of it so users don't need to know about that detail.
 128:  *
 129:  * @var string
 130:  */
 131:     protected $_input = '';
 132: 
 133: /**
 134:  * Constructor
 135:  *
 136:  * @param string $url Trimmed URL string to use. Should not contain the application base path.
 137:  * @param bool $parseEnvironment Set to false to not auto parse the environment. ie. GET, POST and FILES.
 138:  */
 139:     public function __construct($url = null, $parseEnvironment = true) {
 140:         $this->_base();
 141:         if (empty($url)) {
 142:             $url = $this->_url();
 143:         }
 144:         if ($url[0] === '/') {
 145:             $url = substr($url, 1);
 146:         }
 147:         $this->url = $url;
 148: 
 149:         if ($parseEnvironment) {
 150:             $this->_processPost();
 151:             $this->_processGet();
 152:             $this->_processFiles();
 153:         }
 154:         $this->here = $this->base . '/' . $this->url;
 155:     }
 156: 
 157: /**
 158:  * process the post data and set what is there into the object.
 159:  * processed data is available at `$this->data`
 160:  *
 161:  * Will merge POST vars prefixed with `data`, and ones without
 162:  * into a single array. Variables prefixed with `data` will overwrite those without.
 163:  *
 164:  * If you have mixed POST values be careful not to make any top level keys numeric
 165:  * containing arrays. Hash::merge() is used to merge data, and it has possibly
 166:  * unexpected behavior in this situation.
 167:  *
 168:  * @return void
 169:  */
 170:     protected function _processPost() {
 171:         if ($_POST) {
 172:             $this->data = $_POST;
 173:         } elseif (($this->is('put') || $this->is('delete')) &&
 174:             strpos($this->contentType(), 'application/x-www-form-urlencoded') === 0
 175:         ) {
 176:                 $data = $this->_readInput();
 177:                 parse_str($data, $this->data);
 178:         }
 179:         if (ini_get('magic_quotes_gpc') === '1') {
 180:             $this->data = stripslashes_deep($this->data);
 181:         }
 182: 
 183:         $override = null;
 184:         if (env('HTTP_X_HTTP_METHOD_OVERRIDE')) {
 185:             $this->data['_method'] = env('HTTP_X_HTTP_METHOD_OVERRIDE');
 186:             $override = $this->data['_method'];
 187:         }
 188: 
 189:         $isArray = is_array($this->data);
 190:         if ($isArray && isset($this->data['_method'])) {
 191:             if (!empty($_SERVER)) {
 192:                 $_SERVER['REQUEST_METHOD'] = $this->data['_method'];
 193:             } else {
 194:                 $_ENV['REQUEST_METHOD'] = $this->data['_method'];
 195:             }
 196:             $override = $this->data['_method'];
 197:             unset($this->data['_method']);
 198:         }
 199: 
 200:         if ($override && !in_array($override, array('POST', 'PUT', 'PATCH', 'DELETE'))) {
 201:             $this->data = array();
 202:         }
 203: 
 204:         if ($isArray && isset($this->data['data'])) {
 205:             $data = $this->data['data'];
 206:             if (count($this->data) <= 1) {
 207:                 $this->data = $data;
 208:             } else {
 209:                 unset($this->data['data']);
 210:                 $this->data = Hash::merge($this->data, $data);
 211:             }
 212:         }
 213:     }
 214: 
 215: /**
 216:  * Process the GET parameters and move things into the object.
 217:  *
 218:  * @return void
 219:  */
 220:     protected function _processGet() {
 221:         if (ini_get('magic_quotes_gpc') === '1') {
 222:             $query = stripslashes_deep($_GET);
 223:         } else {
 224:             $query = $_GET;
 225:         }
 226: 
 227:         $unsetUrl = '/' . str_replace(array('.', ' '), '_', urldecode($this->url));
 228:         unset($query[$unsetUrl]);
 229:         unset($query[$this->base . $unsetUrl]);
 230:         if (strpos($this->url, '?') !== false) {
 231:             list($this->url, $querystr) = explode('?', $this->url);
 232:             parse_str($querystr, $queryArgs);
 233:             $query += $queryArgs;
 234:         }
 235:         if (isset($this->params['url'])) {
 236:             $query = array_merge($this->params['url'], $query);
 237:         }
 238:         $this->query = $query;
 239:     }
 240: 
 241: /**
 242:  * Get the request uri. Looks in PATH_INFO first, as this is the exact value we need prepared
 243:  * by PHP. Following that, REQUEST_URI, PHP_SELF, HTTP_X_REWRITE_URL and argv are checked in that order.
 244:  * Each of these server variables have the base path, and query strings stripped off
 245:  *
 246:  * @return string URI The CakePHP request path that is being accessed.
 247:  */
 248:     protected function _url() {
 249:         $uri = '';
 250:         if (!empty($_SERVER['PATH_INFO'])) {
 251:             return $_SERVER['PATH_INFO'];
 252:         } elseif (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], '://') === false) {
 253:             $uri = $_SERVER['REQUEST_URI'];
 254:         } elseif (isset($_SERVER['REQUEST_URI'])) {
 255:             $qPosition = strpos($_SERVER['REQUEST_URI'], '?');
 256:             if ($qPosition !== false && strpos($_SERVER['REQUEST_URI'], '://') > $qPosition) {
 257:                 $uri = $_SERVER['REQUEST_URI'];
 258:             } else {
 259:                 $baseUrl = Configure::read('App.fullBaseUrl');
 260:                 if (substr($_SERVER['REQUEST_URI'], 0, strlen($baseUrl)) === $baseUrl) {
 261:                     $uri = substr($_SERVER['REQUEST_URI'], strlen($baseUrl));
 262:                 }
 263:             }
 264:         } elseif (isset($_SERVER['PHP_SELF']) && isset($_SERVER['SCRIPT_NAME'])) {
 265:             $uri = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['PHP_SELF']);
 266:         } elseif (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
 267:             $uri = $_SERVER['HTTP_X_REWRITE_URL'];
 268:         } elseif ($var = env('argv')) {
 269:             $uri = $var[0];
 270:         }
 271: 
 272:         $base = $this->base;
 273: 
 274:         if (strlen($base) > 0 && strpos($uri, $base) === 0) {
 275:             $uri = substr($uri, strlen($base));
 276:         }
 277:         if (strpos($uri, '?') !== false) {
 278:             list($uri) = explode('?', $uri, 2);
 279:         }
 280:         if (empty($uri) || $uri === '/' || $uri === '//' || $uri === '/index.php') {
 281:             $uri = '/';
 282:         }
 283:         $endsWithIndex = '/webroot/index.php';
 284:         $endsWithLength = strlen($endsWithIndex);
 285:         if (strlen($uri) >= $endsWithLength &&
 286:             substr($uri, -$endsWithLength) === $endsWithIndex
 287:         ) {
 288:             $uri = '/';
 289:         }
 290:         return $uri;
 291:     }
 292: 
 293: /**
 294:  * Returns a base URL and sets the proper webroot
 295:  *
 296:  * If CakePHP is called with index.php in the URL even though
 297:  * URL Rewriting is activated (and thus not needed) it swallows
 298:  * the unnecessary part from $base to prevent issue #3318.
 299:  *
 300:  * @return string Base URL
 301:  */
 302:     protected function _base() {
 303:         $dir = $webroot = null;
 304:         $config = Configure::read('App');
 305:         extract($config);
 306: 
 307:         if (!isset($base)) {
 308:             $base = $this->base;
 309:         }
 310:         if ($base !== false) {
 311:             $this->webroot = $base . '/';
 312:             return $this->base = $base;
 313:         }
 314: 
 315:         if (empty($baseUrl)) {
 316:             $base = dirname(env('PHP_SELF'));
 317:             // Clean up additional / which cause following code to fail..
 318:             $base = preg_replace('#/+#', '/', $base);
 319: 
 320:             $indexPos = strpos($base, '/webroot/index.php');
 321:             if ($indexPos !== false) {
 322:                 $base = substr($base, 0, $indexPos) . '/webroot';
 323:             }
 324:             if ($webroot === 'webroot' && $webroot === basename($base)) {
 325:                 $base = dirname($base);
 326:             }
 327:             if ($dir === 'app' && $dir === basename($base)) {
 328:                 $base = dirname($base);
 329:             }
 330: 
 331:             if ($base === DS || $base === '.') {
 332:                 $base = '';
 333:             }
 334:             $base = implode('/', array_map('rawurlencode', explode('/', $base)));
 335:             $this->webroot = $base . '/';
 336: 
 337:             return $this->base = $base;
 338:         }
 339: 
 340:         $file = '/' . basename($baseUrl);
 341:         $base = dirname($baseUrl);
 342: 
 343:         if ($base === DS || $base === '.') {
 344:             $base = '';
 345:         }
 346:         $this->webroot = $base . '/';
 347: 
 348:         $docRoot = env('DOCUMENT_ROOT');
 349:         $docRootContainsWebroot = strpos($docRoot, $dir . DS . $webroot);
 350: 
 351:         if (!empty($base) || !$docRootContainsWebroot) {
 352:             if (strpos($this->webroot, '/' . $dir . '/') === false) {
 353:                 $this->webroot .= $dir . '/';
 354:             }
 355:             if (strpos($this->webroot, '/' . $webroot . '/') === false) {
 356:                 $this->webroot .= $webroot . '/';
 357:             }
 358:         }
 359:         return $this->base = $base . $file;
 360:     }
 361: 
 362: /**
 363:  * Process $_FILES and move things into the object.
 364:  *
 365:  * @return void
 366:  */
 367:     protected function _processFiles() {
 368:         if (isset($_FILES) && is_array($_FILES)) {
 369:             foreach ($_FILES as $name => $data) {
 370:                 if ($name !== 'data') {
 371:                     $this->params['form'][$name] = $data;
 372:                 }
 373:             }
 374:         }
 375: 
 376:         if (isset($_FILES['data'])) {
 377:             foreach ($_FILES['data'] as $key => $data) {
 378:                 $this->_processFileData('', $data, $key);
 379:             }
 380:         }
 381:     }
 382: 
 383: /**
 384:  * Recursively walks the FILES array restructuring the data
 385:  * into something sane and useable.
 386:  *
 387:  * @param string $path The dot separated path to insert $data into.
 388:  * @param array $data The data to traverse/insert.
 389:  * @param string $field The terminal field name, which is the top level key in $_FILES.
 390:  * @return void
 391:  */
 392:     protected function _processFileData($path, $data, $field) {
 393:         foreach ($data as $key => $fields) {
 394:             $newPath = $key;
 395:             if (strlen($path) > 0) {
 396:                 $newPath = $path . '.' . $key;
 397:             }
 398:             if (is_array($fields)) {
 399:                 $this->_processFileData($newPath, $fields, $field);
 400:             } else {
 401:                 $newPath .= '.' . $field;
 402:                 $this->data = Hash::insert($this->data, $newPath, $fields);
 403:             }
 404:         }
 405:     }
 406: 
 407: /**
 408:  * Get the content type used in this request.
 409:  *
 410:  * @return string
 411:  */
 412:     public function contentType() {
 413:         $type = env('CONTENT_TYPE');
 414:         if ($type) {
 415:             return $type;
 416:         }
 417:         return env('HTTP_CONTENT_TYPE');
 418:     }
 419: 
 420: /**
 421:  * Get the IP the client is using, or says they are using.
 422:  *
 423:  * @param bool $safe Use safe = false when you think the user might manipulate their HTTP_CLIENT_IP
 424:  *   header. Setting $safe = false will also look at HTTP_X_FORWARDED_FOR
 425:  * @return string The client IP.
 426:  */
 427:     public function clientIp($safe = true) {
 428:         if (!$safe && env('HTTP_X_FORWARDED_FOR')) {
 429:             $ipaddr = preg_replace('/(?:,.*)/', '', env('HTTP_X_FORWARDED_FOR'));
 430:         } elseif (!$safe && env('HTTP_CLIENT_IP')) {
 431:             $ipaddr = env('HTTP_CLIENT_IP');
 432:         } else {
 433:             $ipaddr = env('REMOTE_ADDR');
 434:         }
 435:         return trim($ipaddr);
 436:     }
 437: 
 438: /**
 439:  * Returns the referer that referred this request.
 440:  *
 441:  * @param bool $local Attempt to return a local address. Local addresses do not contain hostnames.
 442:  * @return string The referring address for this request.
 443:  */
 444:     public function referer($local = false) {
 445:         $ref = env('HTTP_REFERER');
 446: 
 447:         $base = Configure::read('App.fullBaseUrl') . $this->webroot;
 448:         if (!empty($ref) && !empty($base)) {
 449:             if ($local && strpos($ref, $base) === 0) {
 450:                 $ref = substr($ref, strlen($base));
 451:                 if (!strlen($ref) || strpos($ref, '//') === 0) {
 452:                     $ref = '/';
 453:                 }
 454:                 if ($ref[0] !== '/') {
 455:                     $ref = '/' . $ref;
 456:                 }
 457:                 return $ref;
 458:             } elseif (!$local) {
 459:                 return $ref;
 460:             }
 461:         }
 462:         return '/';
 463:     }
 464: 
 465: /**
 466:  * Missing method handler, handles wrapping older style isAjax() type methods
 467:  *
 468:  * @param string $name The method called
 469:  * @param array $params Array of parameters for the method call
 470:  * @return mixed
 471:  * @throws CakeException when an invalid method is called.
 472:  */
 473:     public function __call($name, $params) {
 474:         if (strpos($name, 'is') === 0) {
 475:             $type = strtolower(substr($name, 2));
 476:             return $this->is($type);
 477:         }
 478:         throw new CakeException(__d('cake_dev', 'Method %s does not exist', $name));
 479:     }
 480: 
 481: /**
 482:  * Magic get method allows access to parsed routing parameters directly on the object.
 483:  *
 484:  * Allows access to `$this->params['controller']` via `$this->controller`
 485:  *
 486:  * @param string $name The property being accessed.
 487:  * @return mixed Either the value of the parameter or null.
 488:  */
 489:     public function __get($name) {
 490:         if (isset($this->params[$name])) {
 491:             return $this->params[$name];
 492:         }
 493:         return null;
 494:     }
 495: 
 496: /**
 497:  * Magic isset method allows isset/empty checks
 498:  * on routing parameters.
 499:  *
 500:  * @param string $name The property being accessed.
 501:  * @return bool Existence
 502:  */
 503:     public function __isset($name) {
 504:         return isset($this->params[$name]);
 505:     }
 506: 
 507: /**
 508:  * Check whether or not a Request is a certain type.
 509:  *
 510:  * Uses the built in detection rules as well as additional rules
 511:  * defined with CakeRequest::addDetector(). Any detector can be called
 512:  * as `is($type)` or `is$Type()`.
 513:  *
 514:  * @param string|string[] $type The type of request you want to check. If an array
 515:  *   this method will return true if the request matches any type.
 516:  * @return bool Whether or not the request is the type you are checking.
 517:  */
 518:     public function is($type) {
 519:         if (is_array($type)) {
 520:             foreach ($type as $_type) {
 521:                 if ($this->is($_type)) {
 522:                     return true;
 523:                 }
 524:             }
 525:             return false;
 526:         }
 527:         $type = strtolower($type);
 528:         if (!isset($this->_detectors[$type])) {
 529:             return false;
 530:         }
 531:         $detect = $this->_detectors[$type];
 532:         if (isset($detect['env']) && $this->_environmentDetector($detect)) {
 533:             return true;
 534:         }
 535:         if (isset($detect['header']) && $this->_headerDetector($detect)) {
 536:             return true;
 537:         }
 538:         if (isset($detect['accept']) && $this->_acceptHeaderDetector($detect)) {
 539:             return true;
 540:         }
 541:         if (isset($detect['param']) && $this->_paramDetector($detect)) {
 542:             return true;
 543:         }
 544:         if (isset($detect['callback']) && is_callable($detect['callback'])) {
 545:             return call_user_func($detect['callback'], $this);
 546:         }
 547:         return false;
 548:     }
 549: 
 550: /**
 551:  * Detects if a URL extension is present.
 552:  *
 553:  * @param array $detect Detector options array.
 554:  * @return bool Whether or not the request is the type you are checking.
 555:  */
 556:     protected function _extensionDetector($detect) {
 557:         if (is_string($detect['extension'])) {
 558:             $detect['extension'] = array($detect['extension']);
 559:         }
 560:         if (in_array($this->params['ext'], $detect['extension'])) {
 561:             return true;
 562:         }
 563:         return false;
 564:     }
 565: 
 566: /**
 567:  * Detects if a specific accept header is present.
 568:  *
 569:  * @param array $detect Detector options array.
 570:  * @return bool Whether or not the request is the type you are checking.
 571:  */
 572:     protected function _acceptHeaderDetector($detect) {
 573:         $acceptHeaders = explode(',', (string)env('HTTP_ACCEPT'));
 574:         foreach ($detect['accept'] as $header) {
 575:             if (in_array($header, $acceptHeaders)) {
 576:                 return true;
 577:             }
 578:         }
 579:         return false;
 580:     }
 581: 
 582: /**
 583:  * Detects if a specific header is present.
 584:  *
 585:  * @param array $detect Detector options array.
 586:  * @return bool Whether or not the request is the type you are checking.
 587:  */
 588:     protected function _headerDetector($detect) {
 589:         foreach ($detect['header'] as $header => $value) {
 590:             $header = env('HTTP_' . strtoupper($header));
 591:             if (!is_null($header)) {
 592:                 if (!is_string($value) && !is_bool($value) && is_callable($value)) {
 593:                     return call_user_func($value, $header);
 594:                 }
 595:                 return ($header === $value);
 596:             }
 597:         }
 598:         return false;
 599:     }
 600: 
 601: /**
 602:  * Detects if a specific request parameter is present.
 603:  *
 604:  * @param array $detect Detector options array.
 605:  * @return bool Whether or not the request is the type you are checking.
 606:  */
 607:     protected function _paramDetector($detect) {
 608:         $key = $detect['param'];
 609:         if (isset($detect['value'])) {
 610:             $value = $detect['value'];
 611:             return isset($this->params[$key]) ? $this->params[$key] == $value : false;
 612:         }
 613:         if (isset($detect['options'])) {
 614:             return isset($this->params[$key]) ? in_array($this->params[$key], $detect['options']) : false;
 615:         }
 616:         return false;
 617:     }
 618: 
 619: /**
 620:  * Detects if a specific environment variable is present.
 621:  *
 622:  * @param array $detect Detector options array.
 623:  * @return bool Whether or not the request is the type you are checking.
 624:  */
 625:     protected function _environmentDetector($detect) {
 626:         if (isset($detect['env'])) {
 627:             if (isset($detect['value'])) {
 628:                 return env($detect['env']) == $detect['value'];
 629:             }
 630:             if (isset($detect['pattern'])) {
 631:                 return (bool)preg_match($detect['pattern'], env($detect['env']));
 632:             }
 633:             if (isset($detect['options'])) {
 634:                 $pattern = '/' . implode('|', $detect['options']) . '/i';
 635:                 return (bool)preg_match($pattern, env($detect['env']));
 636:             }
 637:         }
 638:         return false;
 639:     }
 640: 
 641: /**
 642:  * Check that a request matches all the given types.
 643:  *
 644:  * Allows you to test multiple types and union the results.
 645:  * See CakeRequest::is() for how to add additional types and the
 646:  * built-in types.
 647:  *
 648:  * @param array $types The types to check.
 649:  * @return bool Success.
 650:  * @see CakeRequest::is()
 651:  */
 652:     public function isAll(array $types) {
 653:         foreach ($types as $type) {
 654:             if (!$this->is($type)) {
 655:                 return false;
 656:             }
 657:         }
 658:         return true;
 659:     }
 660: 
 661: /**
 662:  * Add a new detector to the list of detectors that a request can use.
 663:  * There are several different formats and types of detectors that can be set.
 664:  *
 665:  * ### Environment value comparison
 666:  *
 667:  * An environment value comparison, compares a value fetched from `env()` to a known value
 668:  * the environment value is equality checked against the provided value.
 669:  *
 670:  * e.g `addDetector('post', array('env' => 'REQUEST_METHOD', 'value' => 'POST'))`
 671:  *
 672:  * ### Pattern value comparison
 673:  *
 674:  * Pattern value comparison allows you to compare a value fetched from `env()` to a regular expression.
 675:  *
 676:  * e.g `addDetector('iphone', array('env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i'));`
 677:  *
 678:  * ### Option based comparison
 679:  *
 680:  * Option based comparisons use a list of options to create a regular expression. Subsequent calls
 681:  * to add an already defined options detector will merge the options.
 682:  *
 683:  * e.g `addDetector('mobile', array('env' => 'HTTP_USER_AGENT', 'options' => array('Fennec')));`
 684:  *
 685:  * ### Callback detectors
 686:  *
 687:  * Callback detectors allow you to provide a 'callback' type to handle the check. The callback will
 688:  * receive the request object as its only parameter.
 689:  *
 690:  * e.g `addDetector('custom', array('callback' => array('SomeClass', 'somemethod')));`
 691:  *
 692:  * ### Request parameter detectors
 693:  *
 694:  * Allows for custom detectors on the request parameters.
 695:  *
 696:  * e.g `addDetector('requested', array('param' => 'requested', 'value' => 1)`
 697:  *
 698:  * You can also make parameter detectors that accept multiple values
 699:  * using the `options` key. This is useful when you want to check
 700:  * if a request parameter is in a list of options.
 701:  *
 702:  * `addDetector('extension', array('param' => 'ext', 'options' => array('pdf', 'csv'))`
 703:  *
 704:  * @param string $name The name of the detector.
 705:  * @param array $options The options for the detector definition. See above.
 706:  * @return void
 707:  */
 708:     public function addDetector($name, $options) {
 709:         $name = strtolower($name);
 710:         if (isset($this->_detectors[$name]) && isset($options['options'])) {
 711:             $options = Hash::merge($this->_detectors[$name], $options);
 712:         }
 713:         $this->_detectors[$name] = $options;
 714:     }
 715: 
 716: /**
 717:  * Add parameters to the request's parsed parameter set. This will overwrite any existing parameters.
 718:  * This modifies the parameters available through `$request->params`.
 719:  *
 720:  * @param array $params Array of parameters to merge in
 721:  * @return self
 722:  */
 723:     public function addParams($params) {
 724:         $this->params = array_merge($this->params, (array)$params);
 725:         return $this;
 726:     }
 727: 
 728: /**
 729:  * Add paths to the requests' paths vars. This will overwrite any existing paths.
 730:  * Provides an easy way to modify, here, webroot and base.
 731:  *
 732:  * @param array $paths Array of paths to merge in
 733:  * @return self
 734:  */
 735:     public function addPaths($paths) {
 736:         foreach (array('webroot', 'here', 'base') as $element) {
 737:             if (isset($paths[$element])) {
 738:                 $this->{$element} = $paths[$element];
 739:             }
 740:         }
 741:         return $this;
 742:     }
 743: 
 744: /**
 745:  * Get the value of the current requests URL. Will include named parameters and querystring arguments.
 746:  *
 747:  * @param bool $base Include the base path, set to false to trim the base path off.
 748:  * @return string the current request URL including query string args.
 749:  */
 750:     public function here($base = true) {
 751:         $url = $this->here;
 752:         if (!empty($this->query)) {
 753:             $url .= '?' . http_build_query($this->query, null, '&');
 754:         }
 755:         if (!$base) {
 756:             $url = preg_replace('/^' . preg_quote($this->base, '/') . '/', '', $url, 1);
 757:         }
 758:         return $url;
 759:     }
 760: 
 761: /**
 762:  * Read an HTTP header from the Request information.
 763:  *
 764:  * @param string $name Name of the header you want.
 765:  * @return mixed Either false on no header being set or the value of the header.
 766:  */
 767:     public static function header($name) {
 768:         $httpName = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
 769:         if (isset($_SERVER[$httpName])) {
 770:             return $_SERVER[$httpName];
 771:         }
 772:         // Use the provided value, in some configurations apache will
 773:         // pass Authorization with no prefix and in Titlecase.
 774:         if (isset($_SERVER[$name])) {
 775:             return $_SERVER[$name];
 776:         }
 777:         return false;
 778:     }
 779: 
 780: /**
 781:  * Get the HTTP method used for this request.
 782:  * There are a few ways to specify a method.
 783:  *
 784:  * - If your client supports it you can use native HTTP methods.
 785:  * - You can set the HTTP-X-Method-Override header.
 786:  * - You can submit an input with the name `_method`
 787:  *
 788:  * Any of these 3 approaches can be used to set the HTTP method used
 789:  * by CakePHP internally, and will effect the result of this method.
 790:  *
 791:  * @return string The name of the HTTP method used.
 792:  */
 793:     public function method() {
 794:         return env('REQUEST_METHOD');
 795:     }
 796: 
 797: /**
 798:  * Get the host that the request was handled on.
 799:  *
 800:  * @param bool $trustProxy Whether or not to trust the proxy host.
 801:  * @return string
 802:  */
 803:     public function host($trustProxy = false) {
 804:         if ($trustProxy) {
 805:             return env('HTTP_X_FORWARDED_HOST');
 806:         }
 807:         return env('HTTP_HOST');
 808:     }
 809: 
 810: /**
 811:  * Get the domain name and include $tldLength segments of the tld.
 812:  *
 813:  * @param int $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
 814:  *   While `example.co.uk` contains 2.
 815:  * @return string Domain name without subdomains.
 816:  */
 817:     public function domain($tldLength = 1) {
 818:         $segments = explode('.', $this->host());
 819:         $domain = array_slice($segments, -1 * ($tldLength + 1));
 820:         return implode('.', $domain);
 821:     }
 822: 
 823: /**
 824:  * Get the subdomains for a host.
 825:  *
 826:  * @param int $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
 827:  *   While `example.co.uk` contains 2.
 828:  * @return array An array of subdomains.
 829:  */
 830:     public function subdomains($tldLength = 1) {
 831:         $segments = explode('.', $this->host());
 832:         return array_slice($segments, 0, -1 * ($tldLength + 1));
 833:     }
 834: 
 835: /**
 836:  * Find out which content types the client accepts or check if they accept a
 837:  * particular type of content.
 838:  *
 839:  * #### Get all types:
 840:  *
 841:  * `$this->request->accepts();`
 842:  *
 843:  * #### Check for a single type:
 844:  *
 845:  * `$this->request->accepts('application/json');`
 846:  *
 847:  * This method will order the returned content types by the preference values indicated
 848:  * by the client.
 849:  *
 850:  * @param string $type The content type to check for. Leave null to get all types a client accepts.
 851:  * @return mixed Either an array of all the types the client accepts or a boolean if they accept the
 852:  *   provided type.
 853:  */
 854:     public function accepts($type = null) {
 855:         $raw = $this->parseAccept();
 856:         $accept = array();
 857:         foreach ($raw as $types) {
 858:             $accept = array_merge($accept, $types);
 859:         }
 860:         if ($type === null) {
 861:             return $accept;
 862:         }
 863:         return in_array($type, $accept);
 864:     }
 865: 
 866: /**
 867:  * Parse the HTTP_ACCEPT header and return a sorted array with content types
 868:  * as the keys, and pref values as the values.
 869:  *
 870:  * Generally you want to use CakeRequest::accept() to get a simple list
 871:  * of the accepted content types.
 872:  *
 873:  * @return array An array of prefValue => array(content/types)
 874:  */
 875:     public function parseAccept() {
 876:         return $this->_parseAcceptWithQualifier($this->header('accept'));
 877:     }
 878: 
 879: /**
 880:  * Get the languages accepted by the client, or check if a specific language is accepted.
 881:  *
 882:  * Get the list of accepted languages:
 883:  *
 884:  * ``` CakeRequest::acceptLanguage(); ```
 885:  *
 886:  * Check if a specific language is accepted:
 887:  *
 888:  * ``` CakeRequest::acceptLanguage('es-es'); ```
 889:  *
 890:  * @param string $language The language to test.
 891:  * @return mixed If a $language is provided, a boolean. Otherwise the array of accepted languages.
 892:  */
 893:     public static function acceptLanguage($language = null) {
 894:         $raw = static::_parseAcceptWithQualifier(static::header('Accept-Language'));
 895:         $accept = array();
 896:         foreach ($raw as $languages) {
 897:             foreach ($languages as &$lang) {
 898:                 if (strpos($lang, '_')) {
 899:                     $lang = str_replace('_', '-', $lang);
 900:                 }
 901:                 $lang = strtolower($lang);
 902:             }
 903:             $accept = array_merge($accept, $languages);
 904:         }
 905:         if ($language === null) {
 906:             return $accept;
 907:         }
 908:         return in_array(strtolower($language), $accept);
 909:     }
 910: 
 911: /**
 912:  * Parse Accept* headers with qualifier options.
 913:  *
 914:  * Only qualifiers will be extracted, any other accept extensions will be
 915:  * discarded as they are not frequently used.
 916:  *
 917:  * @param string $header Header to parse.
 918:  * @return array
 919:  */
 920:     protected static function _parseAcceptWithQualifier($header) {
 921:         $accept = array();
 922:         $header = explode(',', $header);
 923:         foreach (array_filter($header) as $value) {
 924:             $prefValue = '1.0';
 925:             $value = trim($value);
 926: 
 927:             $semiPos = strpos($value, ';');
 928:             if ($semiPos !== false) {
 929:                 $params = explode(';', $value);
 930:                 $value = trim($params[0]);
 931:                 foreach ($params as $param) {
 932:                     $qPos = strpos($param, 'q=');
 933:                     if ($qPos !== false) {
 934:                         $prefValue = substr($param, $qPos + 2);
 935:                     }
 936:                 }
 937:             }
 938: 
 939:             if (!isset($accept[$prefValue])) {
 940:                 $accept[$prefValue] = array();
 941:             }
 942:             if ($prefValue) {
 943:                 $accept[$prefValue][] = $value;
 944:             }
 945:         }
 946:         krsort($accept);
 947:         return $accept;
 948:     }
 949: 
 950: /**
 951:  * Provides a read accessor for `$this->query`. Allows you
 952:  * to use a syntax similar to `CakeSession` for reading URL query data.
 953:  *
 954:  * @param string $name Query string variable name
 955:  * @return mixed The value being read
 956:  */
 957:     public function query($name) {
 958:         return Hash::get($this->query, $name);
 959:     }
 960: 
 961: /**
 962:  * Provides a read/write accessor for `$this->data`. Allows you
 963:  * to use a syntax similar to `CakeSession` for reading post data.
 964:  *
 965:  * ## Reading values.
 966:  *
 967:  * `$request->data('Post.title');`
 968:  *
 969:  * When reading values you will get `null` for keys/values that do not exist.
 970:  *
 971:  * ## Writing values
 972:  *
 973:  * `$request->data('Post.title', 'New post!');`
 974:  *
 975:  * You can write to any value, even paths/keys that do not exist, and the arrays
 976:  * will be created for you.
 977:  *
 978:  * @param string $name Dot separated name of the value to read/write, one or more args.
 979:  * @return mixed|self Either the value being read, or $this so you can chain consecutive writes.
 980:  */
 981:     public function data($name) {
 982:         $args = func_get_args();
 983:         if (count($args) === 2) {
 984:             $this->data = Hash::insert($this->data, $name, $args[1]);
 985:             return $this;
 986:         }
 987:         return Hash::get($this->data, $name);
 988:     }
 989: 
 990: /**
 991:  * Safely access the values in $this->params.
 992:  *
 993:  * @param string $name The name of the parameter to get.
 994:  * @return mixed The value of the provided parameter. Will
 995:  *   return false if the parameter doesn't exist or is falsey.
 996:  */
 997:     public function param($name) {
 998:         $args = func_get_args();
 999:         if (count($args) === 2) {
1000:             $this->params = Hash::insert($this->params, $name, $args[1]);
1001:             return $this;
1002:         }
1003:         if (!isset($this->params[$name])) {
1004:             return Hash::get($this->params, $name, false);
1005:         }
1006:         return $this->params[$name];
1007:     }
1008: 
1009: /**
1010:  * Read data from `php://input`. Useful when interacting with XML or JSON
1011:  * request body content.
1012:  *
1013:  * Getting input with a decoding function:
1014:  *
1015:  * `$this->request->input('json_decode');`
1016:  *
1017:  * Getting input using a decoding function, and additional params:
1018:  *
1019:  * `$this->request->input('Xml::build', array('return' => 'DOMDocument'));`
1020:  *
1021:  * Any additional parameters are applied to the callback in the order they are given.
1022:  *
1023:  * @param string $callback A decoding callback that will convert the string data to another
1024:  *     representation. Leave empty to access the raw input data. You can also
1025:  *     supply additional parameters for the decoding callback using var args, see above.
1026:  * @return mixed The decoded/processed request data.
1027:  */
1028:     public function input($callback = null) {
1029:         $input = $this->_readInput();
1030:         $args = func_get_args();
1031:         if (!empty($args)) {
1032:             $callback = array_shift($args);
1033:             array_unshift($args, $input);
1034:             return call_user_func_array($callback, $args);
1035:         }
1036:         return $input;
1037:     }
1038: 
1039: /**
1040:  * Modify data originally from `php://input`. Useful for altering json/xml data
1041:  * in middleware or DispatcherFilters before it gets to RequestHandlerComponent
1042:  *
1043:  * @param string $input A string to replace original parsed data from input()
1044:  * @return void
1045:  */
1046:     public function setInput($input) {
1047:         $this->_input = $input;
1048:     }
1049: 
1050: /**
1051:  * Allow only certain HTTP request methods. If the request method does not match
1052:  * a 405 error will be shown and the required "Allow" response header will be set.
1053:  *
1054:  * Example:
1055:  *
1056:  * $this->request->allowMethod('post', 'delete');
1057:  * or
1058:  * $this->request->allowMethod(array('post', 'delete'));
1059:  *
1060:  * If the request would be GET, response header "Allow: POST, DELETE" will be set
1061:  * and a 405 error will be returned.
1062:  *
1063:  * @param string|array $methods Allowed HTTP request methods.
1064:  * @return bool true
1065:  * @throws MethodNotAllowedException
1066:  */
1067:     public function allowMethod($methods) {
1068:         if (!is_array($methods)) {
1069:             $methods = func_get_args();
1070:         }
1071:         foreach ($methods as $method) {
1072:             if ($this->is($method)) {
1073:                 return true;
1074:             }
1075:         }
1076:         $allowed = strtoupper(implode(', ', $methods));
1077:         $e = new MethodNotAllowedException();
1078:         $e->responseHeader('Allow', $allowed);
1079:         throw $e;
1080:     }
1081: 
1082: /**
1083:  * Alias of CakeRequest::allowMethod() for backwards compatibility.
1084:  *
1085:  * @param string|array $methods Allowed HTTP request methods.
1086:  * @return bool true
1087:  * @throws MethodNotAllowedException
1088:  * @see CakeRequest::allowMethod()
1089:  * @deprecated 3.0.0 Since 2.5, use CakeRequest::allowMethod() instead.
1090:  */
1091:     public function onlyAllow($methods) {
1092:         if (!is_array($methods)) {
1093:             $methods = func_get_args();
1094:         }
1095:         return $this->allowMethod($methods);
1096:     }
1097: 
1098: /**
1099:  * Read data from php://input, mocked in tests.
1100:  *
1101:  * @return string contents of php://input
1102:  */
1103:     protected function _readInput() {
1104:         if (empty($this->_input)) {
1105:             $fh = fopen('php://input', 'r');
1106:             $content = stream_get_contents($fh);
1107:             fclose($fh);
1108:             $this->_input = $content;
1109:         }
1110:         return $this->_input;
1111:     }
1112: 
1113: /**
1114:  * Array access read implementation
1115:  *
1116:  * @param string $name Name of the key being accessed.
1117:  * @return mixed
1118:  */
1119:     public function offsetGet($name) {
1120:         if (isset($this->params[$name])) {
1121:             return $this->params[$name];
1122:         }
1123:         if ($name === 'url') {
1124:             return $this->query;
1125:         }
1126:         if ($name === 'data') {
1127:             return $this->data;
1128:         }
1129:         return null;
1130:     }
1131: 
1132: /**
1133:  * Array access write implementation
1134:  *
1135:  * @param string $name Name of the key being written
1136:  * @param mixed $value The value being written.
1137:  * @return void
1138:  */
1139:     public function offsetSet($name, $value) {
1140:         $this->params[$name] = $value;
1141:     }
1142: 
1143: /**
1144:  * Array access isset() implementation
1145:  *
1146:  * @param string $name thing to check.
1147:  * @return bool
1148:  */
1149:     public function offsetExists($name) {
1150:         if ($name === 'url' || $name === 'data') {
1151:             return true;
1152:         }
1153:         return isset($this->params[$name]);
1154:     }
1155: 
1156: /**
1157:  * Array access unset() implementation
1158:  *
1159:  * @param string $name Name to unset.
1160:  * @return void
1161:  */
1162:     public function offsetUnset($name) {
1163:         unset($this->params[$name]);
1164:     }
1165: 
1166: }
1167: 
OpenHub
Rackspace
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (GitHub)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • Slack
  • Paid Support

Generated using CakePHP API Docs