Several times I have to check if a request it’s really a HTTP POST and if the data of post was passed in this request too, so these controllers where I need this check always have to check the data, and type of request…
To avoid repeat the code I wrote this method:
1
2
3
4
5
6
7
8
9
protected function _isPOST($data = false) {
if ((isset($this->RequestHandler) && !$this->RequestHandler->isPost()) || ($_SERVER['REQUEST_METHOD'] != 'POST')) {
$this->redirect(null, 405);
exit;
} else if ($data === true && empty($this->data)) {
$this->redirect(null, 400);
exit;
}
}
You can put this method in your AppController
It’s really simple, but useful for me. The code just check if it’s a POST Request if it’s not, bring a HTTP CODE 405, check if the POST data it’s not empty if it is bring a HTTP CODE 400.
And that’s it, now you don’t need wrote codes like this anymore:
1
2
3
4
5
6
7
8
9
10
11
public function my_action() {
if ($this->RequestHandler->isPost()) {
if (!empty($this->data)) {
} else {
}
} else {
}
}
You have just to put this:
1
2
3
public function my_action() {
$this->_isPOST(true);
}
The first argument it’s a boolean one, you pass true if you want to check if the $this->data it’s not empty, otherwise you pass false, or pass nothing.
