CakePHP2.3の
新機能のうち一つ

CakeRequest::onlyAllow() について
自己紹介

• ビール
• Webデザイナー&エンジニア
本題


• CakeRequest::onlyAllow() について
使い方

• $this->request->onlyAllow('post', 'delete');
 • 引数はいくつでも指定できる
 • 配列でも指定できる
    •   $this->request->onlyAllow(array('post', 'delete'));
使いどころ


• セキュアな処理
 • 削除とか
サンプルコード

1 public function delete($id = null) {
2   $this->Post->id = $id;
3   if (!$this->Post->exists()) {
4       throw new NotFoundException(__('Invalid post'));
5   }
6   $this->request->onlyAllow('post', 'delete');
7   if ($this->Post->delete()) {
   ….
具体的にどうなる

• 許可していないリクエストは例外
   →MethodNotAllowedException
   →ステータスコードは 405

• 許可したリクエストなら true を返す
405


• Method Not Allowed
  (禁止されたメソッド)
有効な引数

• 内部でRequest::is()を実行している
 'get', 'post', 'put', 'delete', 'head',
 'options', 'ssl', 'ajax', 'flash', 'mobile',
 'requested'

• 大文字・小文字は問わない
まとめ

• 悪意の有無に関わらず、たったの一行
 で意図しないリクエストによる問題を
 未然に防ぐ事が出来る。

• APIでGET、JSのAjaxなど定番の処理
 で使ってみようかな∼と思います。
ご清聴ありがとうございました

CakeRequest::onlyAllow() について