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.4 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.4
      • 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

Classes

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