Rectangle 27 1

The issue is pretty clear: Your view file is missing, so create it. I don't know what kind of answer you expect from it but what you do is wrong. If you want to return json read this section.

If you really want to just echo a string you need to call $this->_stop(); after the echo. But instead of returning a meaningless string you should in fact return some kind of json object with a proper message and maybe error code and status so that the response can be handled by your javascript.

php - CakePHP Ajax Request not going Internal Server Error - Stack Ove...

php jquery ajax cakephp
Rectangle 27 7

As mentioned above, Exceptions are the way to return an error on an AJAX request in CakePHP. Here is my solution for gaining finer control of what the error looks like. Also, as above, I am using a custom Exception Renderer, but not a custom exception. The default error response is a JSON object like this:

{"name":"An Internal Error Has Occurred", "url": "\/users\/login.json"}

I almost like the way that the default renderer handles AJAX errors; I just want to tweak it a little:

<?php
// File: /app/Lib/Error/CustomExceptionRenderer.php
App::uses('ExceptionRenderer', 'Error');
class CustomExceptionRenderer extends ExceptionRenderer {

    // override
    public function error400($error) {
        $this->_prepareView($error, 'Not Found');
        $this->controller->response->statusCode($error->getCode());

        $this->_outputMessage('error400');
    }

    // override
    public function error500($error) {
        $this->_prepareView($error, 'An Internal Error Has Ocurred.');
        $code = ($error->getCode() > 500 && $error->getCode() < 506) ? $error->getCode() : 500;
        $this->controller->response->statusCode($code);

        $this->_outputMessage('error500');
    }

    private function _prepareView($error, $genericMessage) {
        $message = $error->getMessage();
        if(!Configure::read('debug') && !Configure::read('detailed_exceptions')) {
            $message = __d('cake', $genericMessage);
        }
        $url = $this->controller->request->here();
        $renderVars = array(
            'name' => h($message),
            'url' => h($url),
            );
        if(isset($this->controller->viewVars['csrf_token'])) {
            $renderVars['csrf_token'] = $this->controller->viewVars['csrf_token'];
        }
        $renderVars['_serialize'] = array_keys($renderVars);
        $this->controller->set($renderVars);
    }
}

Then, in bootstrap.php:

Configure::write('Exception.renderer', 'CustomExceptionRenderer');
  • Say I want to return a new CSRF token in my error response, so that if my existing token has been expired before the exception was thrown, I don't get blackholed the next time I try the request. Check out the Security Component documentation for more on CSRF protection.
  • Create a new class in app/Lib/Error. You can extend the default renderer, or not. Since I just want to change a few small things, and to keep the example simple, I'm extending it.
  • Override the methods that the default renderer uses to create the JSON object that will be returned. This is done with via the Request Handler Component, and conforms to best practices. Indeed, the default renderer does the same thing.
  • My solution to the problem of not getting custom error messages in production is to add an optional configuration key. By default this class will show the generic messages in production, but if you have debug set to 0, and you want the specific error messages: Configure::write('detailed_exceptions', 1);
  • Add the new token to the response if it exists. In my case, I have already called Controller::set on the new token in the beforeFilter method of AppController, so it is available in $this->controller->viewVars. There are probably dozens of other ways of accomplishing this.
{
    "name":"The request has been black-holed",
    "url":"\/users\/login.json",
    "csrf_token":"1279f22f9148b6ff30467abaa06d83491c38e940"
}

Any additional data, of any type can be added to the array passed to Controller::set for the same result.

php - Ajax error handling in CakePHP - Stack Overflow

php ajax cakephp error-handling
Rectangle 27 2

Add a request detector

Do not edit the core. If your intention is to submit a patch, don't rely on your patch until after it's accepted - Otherwise you're on a road to divergence and maintaining your own fork of CakePHP.

Once you determine your exact implementation logic you can use a request detector to honor it.

//AppController::beforeFilter
public function beforeFilter() {
    $this->request->addDetector('ssl', array(
        'env' => 'HTTP_X_FORWARDED_PROTO',
        'value' => 'https'
    ));
}

Note that the keys of the $_SERVER global are normalized as all caps and underscore delimited i.e.:

$ curl --header "X-Forwarded-Proto:https" http:://yoursite.com
$_SERVER['HTTP_X_FORWARDED_PROTO']

Yes, it's something you should take care of - either disable direct access to your webservers so that only via the ip of the loadbalancer will it respond at all; or modify your detector so that it does not return true for direct-access requests irrespective of the value of the X-Forwarded-Proto header - as shown in the documentation you can use a callback to perform whatever logic required rather than simply testing the values of some environment variable.

I hadn't heard of request detectors yet - thanks for that pointer. I've got a quick test running on a vanilla CakePHP install, with your beforeFilter and I'm echoing the result of $this->request->is('ssl') in the PagesController->display() method for now, but I'm getting false, even when I send the X-Forwarded-Proto header from my HTTP client. Since X-Forwarded-Proto is an HTTP header, and not an environment variable, will it still get picked up by a call to the env() function in Cake? I don't see that in the env() method in /lib/Cake/basics.php

Thanks for the edit @AD7six - I'll give it a try later but I think you have it nailed!

This does indeed work, but calls to $this->redirect() still generate 302s to HTTP URLs instead of HTTPS URLs. I guess I need to go lower in the stack than the $this->request->is('ssl') call to get that working seamlessly. The hunt goes on!

function redirect redirect($url) { return parent::redirect(str_replace('http', 'https', Router::url($url, true)));}

Yeah, that's what I've been doing for some time. Be nice if it was handled lower down.

php - How can I securely detect SSL in CakePHP behind an nginx reverse...

php cakephp ssl nginx reverse-proxy
Rectangle 27 8

There are a few types of request params in CakePHP 3.0. Let's review them:

$this->request->query()
Html->link('My link', ['my_query_param' => $value])

Passed arguments: The special type of argument is the one that is received by the controller function as an argument. They are accessed either as the argument or by inspecting $this->request->params['pass']. You Build links with passed args depending on the route, but for the default route you just add positional params to the link like Html->link('My link', ['action' => view, $id, $secondPassedArg, $thirdPassedArg])

Request Params: Passed arguments are a subtype of this one. A request param is a value that can live in the request out of the information that could be extracted from the route. Params can be converted to other types of params during their lifetime.

We have effectively created 3 request params with that route: year, month and day and they can be accessed with $this->request->year $this->request->month and $this->request->day. In order to build a link for this we do:

$this->Html->link(
  'My Link',
  ['action' => 'archive', 'year' => $y, 'month' => $m, 'day' => $d]
);

Note that as the route specify those parameters, they are not converted as query string params. Now if we wanted to convert those to passed arguments, we connect this route instead:

Router::connect('/articles/:year/:month/:day',
  ['controller' => 'articles', 'action' => 'archive'],
  ['pass' => ['year', 'month', 'day']]
);
function archive($year, $month, $day) {
  ...
}

Why does CakePHP allow you to choose between the types as it seems cleaner in ASP.NET from what I've seen so far by defaulting to the query strings until you use the router to make it the pretty version (which you see by default in CakePHP via passed parameters). Thanks for the info Jose, much appreciated.

php - CakePHP 3.0 query string parameters vs passed parameters - Stack...

php cakephp cakephp-3.0
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() {
    parent::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 2

This could be an issue with your apache settings:

<FilesMatch \.php$>
    SetHandler application/x-httpd-php
</FilesMatch>

to get the right content types.

I was about to post the same, XD

Note that you should specify that this goes into the .htaccess (just in case they don't notice)

php - Ajax response is JSON on server and STRING on local computer wit...

php ajax json cakephp
Rectangle 27 1

Thanks to ndm's comment, I've checked the Rate Entity and just removed this part which was automatically generated by bake:

protected $_accessible = [
    'rate' => true,
];

php - PatchEntity ignore data from an ajax request in Cakephp 3.0 - St...

php cakephp orm entity cakephp-3.0
Rectangle 27 1

$.ajax({
        url: '/metas/saveMetas',
        data: {
            "model": model,
            "f_key": f_key,
            "pagetitle": pagetitle,
            "keywords": keywords,
            "description": description,
            "niceurl": niceurl
        },
        dataType: 'json',
        complete: function(){
            return false;
        },
        success: function(result) {
            if(typeof result =='object') {
                $('#modal-spinner-seo-update').hide('slow');
                jQuery.each(result, function(field, message) {
                    $('#seo-'+field).next('div.error-message').html(message).fadeIn('fast');
                });
            } else {
                $('#modal-spinner-seo-update').hide('slow', function() {
                    $("#seo-widget-message-success").fadeIn('slow').delay(2000).fadeOut('slow');
                });
            }
            return false;
        }
    });

into a simple JavaScript xmlHttpRequest as following

xhr = new XMLHttpRequest();
    xhr.onreadystatechange=function()
    {
        if (xhr.readyState==4 && xhr.status==200)
        {
            console.log(xhr.responseText);
            if(typeof xhr.responseText =='object') {
                $('#modal-spinner-seo-update').hide('slow');
                jQuery.each(result, function(field, message) {
                    $('#seo-'+field).next('div.error-message').html(message).fadeIn('fast');
                });
            } else {
                $('#modal-spinner-seo-update').hide('slow', function() {
                    $("#seo-widget-message-success").fadeIn('slow').delay(2000).fadeOut('slow');
                });
            }
            return false;
        }
    };
    xhr.open('GET','/metas/saveMetas?model='+model+'&f_key='+f_key+'&pagetitle='+pagetitle+'&keywords='+keywords+'&description='+description+'&niceurl='+niceurl, true );
    xhr.send();

and now everything seems to work fine. But I still do not understand why. Can anyone explain what I did wrong?

javascript - Jquery Ajax Request return forbidden (403) in cakePHP pro...

javascript php jquery ajax cakephp
Rectangle 27 3

I think you need to know about CakePHP Security levels. Try to lower the security of your cakePHP. CakePHP's Config variables documentation. I had written a blog about it also a long ago.

php - CakePHP remember me with Auth - Stack Overflow

php session cakephp authentication cookies
Rectangle 27 3

The session.cookie_domain option only affects writing session cookies, not reading them. It's the user agent that decides whether to send a cookie alongside the request depending on the domain settings that the server responded with when responding with the cookie.

When a cookie is being sent by a user agent, there will be no domain config value, only the cookie name and its value, so PHP couldn't make use of the domain setting even if it wanted to, it simply has no clue where a cookie originally stems from.

On the server side, sessions are always initialized by PHP itself, all CakePHP can do is call session_start(), and the only thing that matters to PHP is the cookie name and its value. If the cookie name matches the configured session cookie name, then its value will be used to identify a possible session (that is where a custom session handler can hook in), and that's all there is to it on the server side with regards to picking up sessions.

What you could break with a wrong cookie_domain setting, is session renewal, as it will destory the session store, and write a cookie with a domain value that will cause the user agent to not send it on subsequent requests.

The documentation book.cakephp.org/3.0/en/development/ isn't clear on this. Specifically the bit which says "if you want your session to persist across all subdomains". If it's using the settings in php.ini anyway, then surely this would happen anyway?

@Andy PHP will use whatever is currently configured, being it hardcoded in the php.ini, or set/overwritten at runtime (which is what CakePHP will do). The example is just an example to illustrate the usage of the ini option. I'd say that the underlying session and cookie mechanisms are PHP/HTTP principles that don't neccesarily need to be elaborated in the CakePHP docs. But that's just my personal opinion, please feel free to open an issue or push a PR with changes for the docs if you think there's need for clarification, improvements are always welcome! github.com/cakephp/docs

php - CakePHP 3 - Session configuration for logging in via a subdomain...

php session cakephp cookies
Rectangle 27 2

Basically $this->request is using for accessing request parameters. Please check this cakephp article. may be it is setting a request parameter like $_POST["action"]="abcd"; Please check.

I see that $this->request is instance of CakeRequest. However, I don't get action property for this class. see api20.cakephp.org/class/cake-request

Yes. Thats correct. But is there any chance for extending that component(RequestHandler) ? Just look into the code for that.

php - What mean with $this->request->action in cakePHP - Stack Overflo...

php cakephp
Rectangle 27 2

You have some lack in your knowledge about how the webserver handling a request when cakephp is installed. Assume that we use apache. In cake's folder structure you can see .htaccess files in the root, app and webroot directories what have url rewrite rules in them. At the end a normal request to a cakephp site will be transformed to a http://site.url.root/app/webroot/index.php?url=original.url

In nutshell to understand it in your point of view: That index.php call the required php files and at least a cakephp app object is built up in the memory with the required models and methods. Then the app object let say start and calls its methods (model, controller and view methods) and at the end it gives back a result to apache what serves it to you.

Therefore the original url path is a "non existent" virtual url.

php - How do I get CakePHP configured so it shows up correctly in my b...

php cakephp
Rectangle 27 3

As suspected in my edit, the problem was related to the server running cgi php. I'm not exactly sure what the issue was, but the CakePhp google group provided this solution:

In app/Config/core.php there is a commented out definition for App.baseUrl. Uncomment it and replace with the following

Configure::write('App.baseUrl', '/mysite/');

Above it, there are comments saying to remove the .htaccess files that you should ignore. The site worked fine with the .htaccess files as their standard values, no RewriteBase needed. The one annoyance was that $this->Html->css() and $this->Html->js() functions did not work, but I only call them in templates, so it's not terrible to hard code them.

If anyone has insight into the cause of these cgi woes, please share. It still feels a bit like a kludge if I can't use all of the Html helpers.

CakePhp 2.0 .htaccess - Stack Overflow

.htaccess cakephp mod-rewrite cakephp-2.0
Rectangle 27 1

jQuery ajax function is expecting a json object and you aren't giving it json

Here are some suggestions for working with ajax in cakephp

  • You need to set the _serialize view variable if you want to return data
$responseData = ['success' => true];
$this->set('responseData', $responseData);
$this->set('_serialize', ['responseData']);

Obligatory references from the docs

There are two ways you can generate data views. The first is by using the _serialize key, and the second is by creating normal template files

The _serialize key is a special view variable that indicates which other view variable(s) should be serialized when using a data view.

javascript - CakePHP 3: Ajax response is returning a 200 response code...

javascript php jquery ajax cakephp
Rectangle 27 1

Check your version of CakePHP. I had this problem with version 2.4.2 and fixed it by upgrading to 2.4.3.

php - CakePHP parserror with _serialize for JSON response - Stack Over...

php jquery ajax json cakephp
Rectangle 27 4

You write that at the time when this problem occurs, you have several clients doing AJAX requests every 3 seconds. This makes it likely that all the PHP workers available at your server are blocked by these AJAX requests. Your web server receives your request for /foobar.php and then has to wait until a PHP worker is free to process your request.

So among the possible solutions for your problem are (without you being more specific what the AJAX is needed for, I need to keep this general):

  • have the AJAX requests go to a static file
  • ensure that PHP really closes the connection when the (AJAX) request is finished, for example with a header("Connection: close"); (though this might not be enough, check the comments on the PHP manual about connection handling)
  • reduce the number of AJAX requests made (to a number worked out in cooperation with your provider)

In general you will need your provider's help with solving this. You did not write which method your provider uses for serving PHP, for example with fpm there is a setting called process.max that can limit your web servers ability to process so many PHP files in parallel.

I already asked this: MaxClients 300, MaxRequestsPerChild 4000, ThreadsPerChild 25.. I would be happy if you can tell me which addtional parameters should I ask to my provider for more information about this problem..

-Making AJAX request is obligatory for me. It is very important for my site to make users easily solve their issues. This requests must point to a PHP function. -"You did not write which method your provider uses for serving PHP" What are the options for this? If you can tell me the alternatives then I can ask to my provider. Do you mean this. -I use jQuery for AJAX requests. So I suppose that jQuery closes the connection after getting the AJAX response.

Yes, I mean something like that. the MaxClients only applies if mod_php is used. If they use fpm then the setting I mentioned above applies.

Thank you. Provider told me that PHP handler is Apache module. So what would I ask more? MaxProcessCount or any other more?

apache - Long Time to First Byte value for an empty php file - Stack O...

php apache .htaccess cakephp mod-php
Rectangle 27 1

is fine for jquery. I'm not experienced with cakephp through

yeah its a PHP framework

Put the whole uploadify package in app/webroot/uploadify, paste the Head section into a view and change the script setting to point to a CakePHP controller action that handles the upload..

php - CakePHP Ajax Image Upload - Stack Overflow

php jquery cakephp image-processing file-upload
Rectangle 27 1

It doesn't work with the latest version of CakePHP, but I think its close to what you need.

Actually, I was looking for something like the above (which is how I stumbled on this Stackoverflow post in the first place), and didn't really find anything that came close to what I was looking for ... so wrote my own Plugin:

All documentation is in the README, and it should just work out of the box on CakePHP 2.0.6 and 2.1.0 (tested on both.) Hope its useful.

php - CakePHP Ajax Image Upload - Stack Overflow

php jquery cakephp image-processing file-upload
Rectangle 27 6

Configure::write('debug', 0);
$this->RequestHandler->respondAs('json');
$this->autoRender = false;            
echo json_encode($data);

With JQuery's $.getJSON method, I'm still getting

Resource interpreted as image but transferred with MIME type text/html.

I've recently used this method in Cake 2.0 (although moved this code to a function in AppController so that any controller can use it without repetition). It seems to work well and allows jQuery (1.7) to auto-detect the content as JSON.

php - How to return the correct content-type for JSON in CakePHP? - St...

php ajax json cakephp content-type
Rectangle 27 6

I make Ajax calls to retrieve JSON content in all of my projects and I've never done most of what you're doing here. The extent of my controller code looks something like this:

public function do_something_ajaxy() {
  Configure::write ( 'debug', 0 );
  $this->autoRender = false;

  /** Business logic as required */

  echo json_encode ( $whatever_should_be_encoded );
}

I make my Ajax calls via jQuery so I suppose that could make a difference, but it would surprise me. In this case, you're problem appears to be in the handler, not with the caller. I'd recommend removing lines 17-23 and replacing them with a simple echo json_encode ( array('response' => $actions[0]) ) statement.

You're also testing for $this->RequestHandler->isGet(). Try testing $this->RequestHandler->isAjax() instead. I'm not sure whether Ajax calls are recognized as by both their type and their method.

I tried doing that before - I just had 'return json_encode' (and I tried 'echo json_encode' too). I was told in the IRC channel that that was a bad way of doing it and the 'right way' is to use a view. I disagreed, but I did it anyway to comply. I'll test isAjax, but given that my ajax call is a get request, isGet should work too. I also make my ajax calls with jQuery.

I've just tried your suggestion (I simplified everything to echo json_encode and used isAjax instead of isGet) and I still get 'text/html' returned.

Sorry, Isaac. I forgot to loop back on this. The content type shouldn't matter as long as the content itself is valid JSON. I avoid views for stuff like this because it's an extra file doing essentially nothing. I have issues with clutter. :-)

php - How to return the correct content-type for JSON in CakePHP? - St...

php ajax json cakephp content-type