问题
I read from the cookbook (sec. 4.2)
CakePHP already protects you against SQL Injection if you use CakePHP's ORM methods (such as find() and save()) and proper array notation (ie. array('field' => $value)) instead of raw SQL. For sanitization against XSS its generally better to save raw HTML in database without modification and sanitize at the time of output/display.
So are we sure that we NEVER need to manually sanitize user data against SQL, provided we restrict to methods such as find() and save()? Especially, is this true if I take my data from $_POST directly instead than from $this->data? In other words suppose I do a find() query using $this->data. Then CakePHP sanitize against SQL when writing the array $this->data or when writing the query for find()?
My second question is for sanitizing data to be displayed. Is Sanitize::html idempotent? So, can I use it in my beforeSave() method, or will it break the second time I save beacuse it is applied again and gives a new result?
回答1:
About this question:
CakePHP sanitize against SQL when writing the array $this->data or when writing the query for find()?
Cakephp does not sanitize $this->data in the controller, if you check the cake code, in Dispatcher::parseParams() http://api13.cakephp.org/view_source/dispatcher/#line-244 you will see that when $_POST is copied to controller data the values are not sanitized.
However, using $_POST is not recommended because you will loose all the cake's magic that you gain when using the form helper
回答2:
Woah - If your taking your data directly from $_POST than you should absolutely sanitize the data if you are planning on publishing the data on any pages to come. I remember about 2 years ago a large scare because it was revealed that simple SQL injection would allow cake 1.1 sites to be exploited due to the layout of select queries used to login.
However many users intentionally used the old rule for input fields that would be used in SQL:
"To protect against SQL injection, user input must not directly be embedded in SQL statements. Instead, user input must be escaped....."
SO, yes, that was a seperate issue, but same idea -- although CakePHP is boss, and does alot for us, we should never trust its security blindy. The performance impact of scrubbing data yourself is nearly nil. So just do it.
回答3:
No it wont affect you. You can use it in before_save()
. You will need sanitisation if you use any custom query function i.e functions where you can use your own query
来源:https://stackoverflow.com/questions/2168089/when-to-do-sanitization-in-cakephp