Rectangle 27 11


Will set the status code when Cake is ready to send the response. CakeResponse::send() expects to send the status code and message, so in my tests I think my using header() was getting overwritten. using $this->header('HTTP/1.1 400 Bad Request') doesn't work either because Cake expects any call to $this->header to be split on a colon ex: $this->header('Location: ...')

+1 for a CakePHP 2.x answer ($this->response->...) which may help current visitors from Google, etc. (For those visitors: the answers dated 2009 are for the CakePHP 1.x codebase)

This will work, but Exceptions tend to be preferred for these types of situations in CakePHP 2. They abort controller execution immediately, and they trigger cake's standard error handling process.

Exceptions are better for 4xx and 5xx statuses, but if you need to (for example) return 201 to a POST request, this might be the way to go.

How do you specify an HTTP status code in Cakephp? - Stack Overflow

Rectangle 27 35

EDIT - This question is quite old and covers different versions of the CakePHP framework. Following is a summary of which version each answer applies to. Don't forget to vote on the solution that helps most.

By looking at the relevant API code from the previous comment, it seems you can call Controller::header($status) to output a header without redirection. In your case, the proper usage is most likely:

$this->header('HTTP/1.1 403 Forbidden');

Also, the code above only outputs the header, so you may want to end execution with return false, die, exit, or something similar.

This answers the question more precisely than my answer. Still, I think it's useful to be able to redirect the user to a custom page in this case, it's nicer than a blank 'the server responded this' page.

Looking at the body of that method, it seems to be a wrapper around a built in function called header.

since all of cakephp is actually more php, indeed most stuff could be boiled to 'a wrapper around a built-in function'. The idea is that your development is eased by the wrapping, and that the performance overhead is negligible.

How do you specify an HTTP status code in Cakephp? - Stack Overflow

Rectangle 27 47

$this -> render('TestView/index');

As the answer above mention, you can use $this->set to pass variable to the View.

However, if that doesn't give you what you want I'm guessing that you also want to action to display another layout (non-default layout). You can try doing $this -> layout = 'layoutname'; (Layouts are in the layout folder, default on is default.ctp)

Note: CakePHP's controller isn't designed to be able to pass data to a non-view file (like .php). CakePHP's views should be ending with .ctp

maybe I'm late.. but if you set variable "*_for_layout" will be available in layout too.

For me, I needed to put a / in front of the path (e.g. /TestView/index).


The render() method will stop the controller execution and whatever code is after that line will be omitted. Setting the view property instead is a better idea, the answer from @Sabin Neagu should be accepted.

php - Rendering controller to a different view in CakePHP - Stack Over...

php cakephp
Rectangle 27 13

I would recommend that you check the documentation first.

Recursive defines the amount of data that will be fetched from the database, Cakephp by default will get the data of the Model/Table that you're querying for and the data of the Models/Tables that are linked to the main Model/table (hasmany, belongsto, etc.)

By setting recursive, you're forcing Cakephp to only fetch a certain amount of data, it can be more or less, depending on how much deep are the association between the models/tables and the number specified in recursive.

Setting recursive to -1 will only get the data of the model that you're querying for, setting it higher will ask Cakephp to fetch deeper association.

Lets say that in our app we have authors that sell books and they get commented by readers.

If we don't set recursive while fetching the list of authors, Cakephp will get the list of authors their books and comments.

$authors = $this->Author->find('all');

The problem is that for each list display, Cakephp and the database are dealing with a lot of unnecessary data ! which in return impact the performance of your http & database server.

Imagine that the list is shown 10/s and each list shows 20 authors (authors who can have from 1 book to *, lets say 10 books as an average number for this example with 5 comments each) do the math and you will see that the servers are processing a lot of unnecessary data which wont be used in the end.

The user want to only see the authors list, so there's no need to fetch all the books and comments unless you're going to process them in the controller or to display them in the views. We can do so by setting recursive to -1.

You may want to optimize your queries so it fetches only the fields that you're going to use, it will boost the overall performance, but that's another subject.

Sometimes you will find yourself wanting to do the reverse of that : lets say that the app update the Auth Session variable whenever the user log-in (update ip, browser info, oauth token, group info etc.) and that the app use all the user relatives info to adapt the user experience, for example if the user belongs to a certain group shows relative info&options to that particular group, if the user has allowed the app to access certain account info of a third party provider (google ?) show services that uses that kind of data - lets say show google+ feed or something - etc.

It would be a lot easier to fetch all the relative info of the user once he's logged in and store it in Session, which in return will be used by views to adapt the user experience. One way of doing so would be to fetch the relative data one by one and storing it in Session or simply set recursive to 2 and store the result in Session, it will fetch all the relative data of the user model.

recursive allow you to define the amount of data to get from the database. Lets say that the Author has many publication.

if you specify -1 for recursive before getting a certain author from the database like so:

$this->Author->recursive = -1; 
$author = $this->Author->findByName('Someone');

you would get only the Author information/you will get information only from the the Authors table and none from the related tables like publications.

you can see this by yourself by using this code:

//only author info

$this->Author->recursive = -1; 
$author = $this->Author->findByName('Someone');

//display the result

//get the author and related publications info
$this->Author->recursise = 1;
$authorAndPublications =  $this->Author->findByName('Someone');

//display result

The recursive property then specify how much information do you want from your database.

lets suppose each author has at least 10 publications and you want to query the database to find the authors, if you didn't specify the recursive property, Cakephp will get all the authors and their publications too!! so lets say 50 authors * 10 publications..... you get the picture, you are querying for a ton of unnecessary data.

it mater a lot if it is a high traffic site since for example at each authors list display you query for 500 unnecessary publications informations(that wont be used) just to display some information of the 50 authors in a list/table.

by using recursive = -1; before querying for the authors you ease the strain on the database which result in better reactivity and performance.

what is the meaning of recursive in cakephp? - Stack Overflow

Rectangle 27 16

Edit (2015): Please see the Awesome CakePHP list for current file plugins (2.x branch here)

You might consider using the Media plugin that was talked about at the last CakeFest. It is fairly comprehensive, containing features such as creating file variations (ie. thumbnails of images or video), helpers for outputting different types of files, and elements to help create multiple-file upload forms more quickly; and also had a strong focus on security from the outset as I can gather from the slides. I use it in production and find it works well, plus it seems to be under more active development than other options I have seen if that's anything to go by (eg. MeioUpload behavior, Uploader plugin, FileUpload plugin and various Bakery/blog posts on the topic).

Let me shamelessly add Upload Pack to the list

Uploader and Upload Pack are the top 2 supported CakePHP 2.x libs that I have found after half a day of research and attempts at implementation.

Upload Plugin 2.0 by Jose Diaz-Gonzalez seems like a good choice now.

php - Best practice to upload files in CakePHP - Stack Overflow

php forms cakephp file-upload cakephp-1.3
Rectangle 27 29

I would not advice to use the method requestAction but rather import, and instantiate the needed controller.

CakePHP doc says about requestAction that:

"It is rarely appropriate to use in a controller or model"

Once you imported and loaded the controller you can call any method of this controller with its parameters.

  //Import controller
  App::import('Controller', 'Posts');

  class CommentsController extends AppController {
    $Posts = new PostsController;
    //Load model, components...

    function index($passArray = array(1,2,3)) {
      //Call a method from PostsController with parameter

thanks for your reply. yes I have heard that rumor about requestAction. wonder why it's not encouraged. Anyway, 'Import' is an alternate solution, thanks.

I agree, this is best, I had been using requestaction but it quickly shows why its not good, if you need to pass in a string that contains anything but basic text it won't work right, since its using the url method so it can't have special characters and if you use "/" in a string htis will break it into separate variables

Using one controller action in another is quite common in a large app. Is there any news on if Cake will implement a standard single command to do so other than requestAction that even the documentation states has poor performance.

sorry for being that old the post to ask, but after loading the model and using it, is it necessary to unload it?

The variables defined need to go in a method, or perhaps this class constructor. But apart from that, I consider this a much cleaner solution than the other answer. Thanks!

CakePHP: best way to call an action of another controller with array a...

arrays cakephp parameters
Rectangle 27 3

The flow control method youll use most often is redirect(). This method takes its first parameter in the form of a CakePHP-relative URL. When a user has successfully placed an order, you might wish to redirect them to a receipt screen. The second parameter of redirect() allows you to define an HTTP status code to accompany the redirect. You may want to use 301 (moved permanently) or 303 (see other), depending on the nature of the redirect.

The method will issue an exit() after the redirect unless you set the third parameter to false.

But I don't want to send a 3xx status code back. Even if this works, it seems wrong.

You can send any status code back, the 303 are just an example.

This is perfect for 3xx redirect status codes. Definitely a horrible idea for everything else, like the user's 403.

How do you specify an HTTP status code in Cakephp? - Stack Overflow

Rectangle 27 7

To achieve a json/xml render view in your cakephp 3 application, you need to edit two file in your application

public function initialize() {
    $this->loadComponent('RequestHandler');/*This line loads the required RequestHandler Component*/
Router::scope('/', function ($routes) {
    $routes->extensions(['json', 'xml', 'ajax']);
    /*Other route definitions as already existing*/

You may now load a json view by adding .json or xml by adding .xml to the link that normally loads your html.

php - Cakephp 3 : Json render View not working - Stack Overflow

php ajax json cakephp
Rectangle 27 14

There can be following reasons for 500 Internal Server Error in CakePHP application:

  • Your .htaccess files are not correct. See Here for details
  • Permissions of folders are not correct. If CakePHP app is Group Writable i.e. 777 then webserver gives 500 error for safety.
  • You are missing Database Connection. Correct database configuration according to Webhost because most of times local and production server databases have different details.
  • Delete the content of your tmp folder. It is best practice that you must delete cache if you move your application from one place to another.
  • If not succeeded check your Apache Error Log. If using Linux /var/log/apache2/error.log

Good @Echo .. Usually 500 error is basic stuffs

@Love Opensource i following your step. but not success i got same error please help.

Check your Apache Error Log. If using Linux /var/log/apache2/error.log

dreamhost - CakePHP 500 Internal Server Error - Stack Overflow

cakephp dreamhost internal-server-error
Rectangle 27 4

(0) .htaccess in ROOT FOLDER

#Action php /cgi-php52/php
#AddHandler php52 .php

# BEGIN WordPress
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteRule ^cakeapp/(.*)$ /cakeapp/$1 [L,QSA]
 RewriteRule ^index\.php$ - [L]
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule . /index.php [L]
# END WordPress

(1) .htaccess in the CAKEAPP-Folder

<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /cakeapp
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteRule ^(.*)$ index.php [QSA,L]

.htaccess / mod_rewrite.c : CakePHP application in a subfolder where t...

wordpress .htaccess cakephp mod-rewrite
Rectangle 27 4

You can do it easily by use StartDate and EndDate. Add the condition like this

'conditions' => array('date(YourModel.addeddate) BETWEEN ? AND ?' => array($sdate,$edate)

Now the question how you will get this month this week this year. You can use this below code.

cakephp TimeHelper
$sdate = $this->Time->format('y-m-d','last saturday');
$edate = $this->Time->format('y-m-d',time());
$sdate = $this->Time->format('y-01-01',time());
$edate = $this->Time->format('y-m-d',time());
$sdate = date('y-m-d', strtotime("last saturday"));
$edate = date("y-m-d");
$sdate = date('y-m-01');
$edate = date("y-m-d");
$sdate = date('y-01-01');
$edate = date("y-m-d");

Now if you want to get last 7 days or last 30 days, you can use strtotime.

$sdate = date('Y-m-d', strtotime("-1 year"));
$edate = date("y-m-d");

Hi , can you please again check your date format ? it seems there is some thing wrong with your $sdate and $edate format.

php - How to search data with This Week, This month, This Year in Cake...

php mysql cakephp cakephp-2.0
Rectangle 27 2

Assuming you have username and email both fields in your users table

public function beforeFilter() {
    if ($this->request->is('post') && $this->action == 'login') {
        $username = $this->request->data['User']['username'];
        if (filter_var($username, FILTER_VALIDATE_EMAIL)) {
            $this->Auth->authenticate['Form']['fields']['username'] = 'email';
            $this->request->data['User']['email'] = $username;

This code will work for CakePHP 2.x, not tested on version 3.x, you should have email field in your user's table.

CakePHP login by Username Or Email using Auth component - Stack Overfl...

Rectangle 27 3

From the documentation v1.3, v2.0:

The recursive property defines how deep CakePHP should go to fetch associated model data via find(), findAll() and read() methods.

Imagine your application features Groups which belong to a domain and have many Users which in turn have many Articles. You can set $recursive to different values based on the amount of data you want back from a $this->Group->find() call:

Set it no higher than you need. Having CakePHP fetch data you arent going to use slows your app unnecessarily. Also note that the default recursive level is 1.

what is the meaning of recursive in cakephp? - Stack Overflow

Rectangle 27 21

CakePHP3 uses a different hashing algorithm by default than 2 (bcrypt vs. SHA1), so you need to make your password length longer. Change your password field to VARCHAR(255) to be safe.

When CakePHP 3 tries to identify your in-memory hashed password from this->Auth->identify() vs. the hashed password in the database, it will never match because some characters are missing. Changing to 255 is more than needed, but can help future proof if an even more secure hash is used in the future. 255 is recommended because the the character count can be stored in one byte.

php - Login [ Auth->identify() ] always false on CakePHP 3 - Stack Ove...

php cakephp authentication login cakephp-3.0
Rectangle 27 7

What you have in your question after your Edit is the intended way in which CakePHP 3 allows you to use different/dynamic validation rules per use case.

use Cake\Validation\Validator;
class UsersTable extends Table {
    public function validationDefault(Validator $validator) {    
        //Some rules...

        $validator->add('email', [
            'unique' => [
                'message'   => 'This value is already used',
                'provider'  => 'table',
                'rule'      => 'validateUnique'

        //Some rules...

        return $validator;

    public function validationOnlyCheck(Validator $validator) {
        $validator = $this->validationDefault($validator);
        $validator->remove('email', 'unique');
        return $validator;
$user = $this->Users->newEntity($this->request->data(), [
    'validate' => 'OnlyCheck'

CakePHP 3.x: how to edit a validation rule on the fly - Stack Overflow

validation cakephp cakephp-3.0
Rectangle 27 5

First off, you should follow the Blog tutorial on the CakePHP cook book :

It's a great example and walks you through all the main stuff.

CakePHP follows an MVC structure and maps the URLs to controller/actions (using routes)

In your example, if you haven't changed the default routing, actually maps to the index method in your ProfileController. This method uses the view in /views/profiles/index.ctp to display output.

First follow the tutorial and read up on the CookBook to figure out what all this means. It's very easy to learn and they have some good documentation. Also check out code generation in CakePHP. It helps you create your apps faster (if used properly).

i'l give it a shot, thankyou.

php - cakephp overviews - Stack Overflow

php oop cakephp
Rectangle 27 2

RewriteRule ^cakephp/(.*)$ /cakephp/$1 [L,QSA]

All the rest is handled with the regular cakephp setup.

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

.htaccess - Set up CakePHP in a subdirectory; Wordpress is installed i...

wordpress .htaccess cakephp mod-rewrite subdirectory
Rectangle 27 1

$response = $this->response->withStatus(403);
return $response;

For versions before CakePHP 3.3.x you can use the same style as CakePHP 2.x:


Note that using the PHP function directly also works (http_response_code(403); die();), though using the response object seems like the intended method.

How do you specify an HTTP status code in Cakephp? - Stack Overflow

Rectangle 27 4

$Date= $this->Date->find('all',array('fields'=>array('Date.created')));

foreach ($Date as $key => $value) {
   $date['date'] = date('d-m-Y',strtotime($value['Date']['created']));

echo "<pre>";

I have made a small demo in CakePHP and It works fine. I have written it in my controller. You should try it.

You can set your date format as per you requirement.

php - How to change default date format in cakephp? - Stack Overflow

php cakephp cakephp-2.0
Rectangle 27 20

Use a shell

The 'Cake Way' of using a CakePHP application in cron jobs would be creating shell and then calling it as a cron job.

i.e. Create a shell to do the task, and then add it to crontab (crontab -e on linux machine):

0 * * * *       cd /path/to/app/ && Console/cake your_shell_name params

Reputation score is clearly not linked to answer quality. This is the correct way of doing things.

cd /path/to/app/ && Console/cake your_shell_name params

cakephp - How to setup cronjobs in cake php? - Stack Overflow