21

How can I access a GET request in CAKEPHP ?

If I am passing a variable in the url

http://samplesite.com/page?key1=value1&key2=value2

Should I use $_GET or $this->params to get the values in controller? What is the standard in CAKEPHP ?

declan
  • 5,605
  • 3
  • 39
  • 43
AnNaMaLaI
  • 4,064
  • 11
  • 53
  • 93

6 Answers6

28

In CakePHP 2.0 this appears to have changed. According to the documentation you can access $this->request->query or $this->request['url'].

// url is /posts/index?page=1&sort=title
$this->request->query['page'];

// You can also access it via array access
$this->request['url']['page'];

http://book.cakephp.org/2.0/en/controllers/request-response.html

Code Commander
  • 16,771
  • 8
  • 64
  • 65
25

The standard way to do this in Cake is to use $this->params.

$value1 = $this->params['url']['key1'];
$value2 = $this->params['url']['key2'];

According to the CakePHP book, "the most common use of $this->params is to access information that has been handed to the controller via GET or POST operations."

See here.

declan
  • 5,605
  • 3
  • 39
  • 43
  • Thanks Dude... Shall i avoid to use $_GET in cakephp? – AnNaMaLaI May 26 '11 at 06:37
  • 1
    @cakephp.saint Yeah, I typically don't access $_GET or $_POST directly when i'm working in Cake. I just updated my answer with a link to the manual. – declan May 26 '11 at 06:44
8

And now that we have CakePHP 3; you can still use $this->request->query('search') in your views.

And in CakePHP 3.5 + you can use $this->request->getQuery('search')

http://book.cakephp.org/3.0/en/controllers/request-response.html#request-parameters

Hamidreza
  • 694
  • 6
  • 19
Melvin
  • 3,421
  • 2
  • 37
  • 41
1

According to CakePHP 4.0.2

$this->request->getQuery()

will give you the whole query strings as an array

and for specific query

$this->request->getQuery('keywords')

https://book.cakephp.org/3/en/controllers/request-response.html

sh6210
  • 4,190
  • 1
  • 37
  • 27
0

You can do this only to get URL params,

$this->request->pass;  //Array of all parameters in URL
bikash.bilz
  • 821
  • 1
  • 13
  • 33
0

According to CakePHP documentation Query String Parameters

// URL is /posts/index?page=1&sort=title
$page = $this->request->getQuery('page');

// Prior to 3.4.0
$page = $this->request->query('page');

To access the all keys from URL You have to use

$data = $this->request->getQuery();
echo "<pre>";print_r($data ); die('MMS');

Output

<pre>Array
(
    [key1] => value
    [key2] => value
    ...........
)
Mannu saraswat
  • 1,061
  • 8
  • 15