I have a problem with sanitization. In AppController I'm using Sanitization utility but It doesn't work. When I want to call my update It fails because of ' slash in my input text. I'm using CakePHP 2.3.6.
function beforeFilter(){
if(!empty($this->data)){
App::uses('Sanitize', 'Utility');
$this->request->data = Sanitize::clean($this->data, array('remove_html'=>true,'encode'=>false,'unicode'=>false,'backslash'=>true, 'escape'=>false));
}
}
Controller code:
$this->ClientProfile->updateAll(
array('ClientProfile.location'=>"'".$this->User->data['ClientProfile']['location']."'"),
array('ClientProfile.user_id'=>$userdata['id'])
);
Any ideas?
Try using Sanitize::escape() instead of Sanitize::clean(). As it's written in the documentation,
Sanitize::escape()
Makes a string SQL-safe.
You may also move data sanitization directly to updateAll() method call. By doing this you will know that updateAll() method will get sanitized data, no matter what happened with this data in other parts of your script.
Related
I have done a code, in which i create events. When i create event there was a field named "detailed_address" which i have removed now, from database, from model,from the edit page, from every where.
Creating an event works fine. but when i edit that event and save it, there is error as:
The detailed address field is required.
I have checked my code for at-least 5 times there is no word detailed address now used.
controller methods:
public function update(EventRequest $request, $id)
{
$event = Event::findOrFail($id);
$input = $request->all();
$input['days_of_week'] = serialize(Input::get('days_of_week'));
$query = $event->update($input);
return redirect('event');
}
public function store(Request $request)
{
$checkbox = Input::get('days_of_week');
$checkbox_selection = Input::get('agree');
$input = $request->all();
$input['days_of_week'] = serialize($checkbox);
$query = Event::create($input);
return view('event.create');
}
Can any one tell what will be my problem?
As #manix suggested, try running php artisan clear-compiled, then i'd suggest running php artisan cache:clear as well just to make doubly sure it's not a cache issue.
Something that could also be worth looking into is your requests folder (app\http\requests), if you weren't validating the input on the controller it was likely being done via requests which might still be checking for input that isn't coming through.
Is the field also still registered as mass assignable on the model?
Can't see why it'd throw a validation error but it's worth making doubly sure it's gone from there too
I want to serve JSONP content with CakePHP and was wondering what's the proper way of doing it so.
Currently I'm able to serve JSON content automatically by following this CakePHP guide.
Ok, I found a solution on this site. Basically you override the afterFilter method with:
public function afterFilter() {
parent::afterFilter();
if (empty($this->request->query['callback']) || $this->response->type() != 'application/json') {
return;
}
// jsonp response
App::uses('Sanitize', 'Utility');
$callbackFuncName = Sanitize::clean($this->request->query['callback']);
$out = $this->response->body();
$out = sprintf("%s(%s)", $callbackFuncName, $out);
$this->response->body($out);
}
I hope it helps someone else as well.
I've as yet not found a complete example of how to correctly return JSONP using CakePHP 2, so I'm going to write it down. OP asks for the correct way, but his answer doesn't use the native options available now in 2.4. For 2.4+, this is the correct method, straight from their documentation:
Set up your views to accept/use JSON (documentation):
Add Router::parseExtensions('json'); to your routes.php config file. This tells Cake to accept .json URI extensions
Add RequestHandler to the list of components in the controller you're going to be using
Cake gets smart here, and now offers you different views for normal requests and JSON/XML etc. requests, allowing you flexibility in how to return those results, if needed. You should now be able to access an action in your controller by:
using the URI /controller/action (which would use the view in /view/controller/action.ctp), OR
using the URI /controller/action.json (which would use the view in /view/controller/json/action.ctp)
If you don't want to define those views i.e. you don't need to do any further processing, and the response is ready to go, you can tell CakePHP to ignore the views and return the data immediately using _serialize. Using _serialize will tell Cake to format your response in the correct format (XML, JSON etc.), set the headers and return it as needed without you needing to do anything else (documentation). To take advantage of this magic:
Set the variables you want to return as you would a view variable i.e. $this->set('post', $post);
Tell Cake to serialize it into XML, JSON etc. by calling $this->set('_serialize', array('posts'));, where the parameter is the view variable you just set in the previous line
And that's it. All headers and responses will be taken over by Cake. This just leaves the JSONP to get working (documentation):
Tell Cake to consider the request a JSONP request by setting $this->set('_jsonp', true);, and Cake will go find the callback function name parameter, and format the response to work with that callback function name. Literally, setting that one parameter does all the work for you.
So, assuming you've set up Cake to accept .json requests, this is what your typical action could look like to work with JSONP:
public function getTheFirstPost()
$post = $this->Post->find('first');
$this->set(array(
'post' => $post, <-- Set the post in the view
'_serialize' => array('post'), <-- Tell cake to use that post
'_jsonp' => true <-- And wrap it in the callback function
)
);
And the JS:
$.ajax({
url: "/controller/get-the-first-post.json",
context: document.body,
dataType: 'jsonp'
}).done(function (data) {
console.log(data);
});
For CakePHP 2.4 and above, you can do this instead.
http://book.cakephp.org/2.0/en/views/json-and-xml-views.html#jsonp-response
So you can simply write:
$this->set('_jsonp', true);
in the relevant action.
Or you can simply write:
/**
*
* beforeRender method
*
* #return void
*/
public function beforeRender() {
parent::beforeRender();
$this->set('_jsonp', true);
}
My code looks something like this:
if ($this->request->is('ajax')) {
$this->Comment->Save();
$this->set('comment', $this->Comment->read());
$this->set('_serialize', array('comment');
}
Instead of responding with Ajax, I get an error that a view is missing. Is there something else that's needed to respond with json? I thought this was handled "automagically" with the response helper.
By enabling RequestHandlerComponent in your application, and enabling support for the xml
and or json extensions, you can automatically leverage the new view classes.
So you still need to enable a few things:
Add
public $components = array('RequestHandler');
and in routes.php
Router::parseExtensions(array('json'));
You may have to have your url look like controller/action.json for the automagic to work. You could just add $this->viewClass = 'Json' in the controller, though (not 100% sure on this).
I am currently working on an export function in cakephp app and im doing a query that is getting around 10,000 rows each export which cake can handle but debug_kit seems to be using lot of memory and putting me over 128mb of memory used.
I have tried tried writing this in the top of the function but debugkit is still getting involved and using large amounts of memory.
Configure::write('debug',0);
HyperCas is correct in suggesting the beforeFilter() callback as an appropriate solution.
The code could look something like this in the controller where the action (ie, export) resides:
function beforeFilter() {
// filter actions which should not output debug messages
if(in_array($this->action, array('export'))) {
Configure::write('debug', 0);
}
}
You would adjust array('export') to include all the actions you want to prevent debug.
Just to improve Benjamin Pearson's answer. Unload the component instead of turning debugging off.
public function beforeFilter() {
parent::beforeFilter();
if(in_array($this->action, array('export'))) {
$this->Components->unload('DebugKit.Toolbar');
}
}
Use
Configure::write('debug',0);
in /app/config/core.php
Or use it in the beforeFilter() callback on the controller. That would stop the debugging for the entire controller if you don't check manually for the current action (in $this->params['action']).
If your model has multiple associations you should take a look at the containable behavior
http://book.cakephp.org/view/51/Controller-Attributes
you can also switch the debug level in the config.php to 0. this will disable the debug kit automaticaly + your application will use even less memory.
Disable debug_kit on the fly
class AppController extends Controller {
public function beforeFilter() {
Configure::write('debug', 0);
}
}
in cakephp3 open bootstrap.php file in config folder
comments or remove the DebugKit loading
if (Configure::read('debug')) {
// Plugin::load('DebugKit', ['bootstrap' => true]);
}
thats all .. it will unload the DebugKit from your application
I have problem with cakephp's Session->write method.
If I set a value like $_SESSION['..'] i'm able to read it back. But if I use the write method it's not working.
My problem is same as here: http://www.nabble.com/Session-problem-td16684956.html
The same code was working in windows but it's not working after I moved to linux.
Any permission problem would be the reason? (but i have given rw permission fully for the cake app directory).
code sample: in the link: http://www.nabble.com/Session-problem-td16684956.html
Configure::write('Session.save', 'php');
Configure::write('Session.cookie', 'CAKEPHP');
Configure::write('Session.start', true);
Configure::write('Session.checkAgent', false);
Configure::write('Security.level', 'medium');
cake version: 1.2.3.8166
Some steps to ensure it's not you:
clear the cache in your /app/tmp
check and recheck that your /app/tmp is world-writable recursively (that means drwxrwxrwx for all folders inside)
use Firebug to check your session cookie, maybe something has gone wrong with it
Last but not least, try to move your session persistence to your database (see: Session.save), just to test things out that way, you never know what you'll find.
Hopefully you'll find something if you try all these.
You should also try to use Cache::read and Cache::write
if (($session = Cache::read('session')) === false)
{
$session = 'some values';
Cache::write('session', $session);
}
Firstly, it will try to initialize Cache::read. If it returns false, Cache::write
will take part to store the values in sessions.
Prabu,
While I suspect the Configure::write() call will sometimes correctly set the session information (at least it looks like it might work), the Cake convention (aka the CakeWay) is to use the Session helper. I believe it is included by default in all Cake controllers; if not, you can always declare your controller as such:
class UsersController extends AppController {
...
var $helpers = array( 'Session', ... )
...
}
Then, when you want to write info to the session, just call:
$this->Session->write( 'checkAgent', false );
To read back values, use:
$this->Session->read( 'checkAgent');
For more information on the Session helper, check out the CakeBook # http://book.cakephp.org/view/484/Session