How do you escape SQL data in CakePHP?
For some reason the AppModel->updateAll()
method does not escape data passed to it. Looking over the documentation though, I can't find anything on how you actually escape data with CakePHP.
Down in datasources/dbo/开发者_如何学Pythondbo_mysql.php
I found the value()
method that seems to just use mysql_real_escape_string()
- but how do you access that method from up in the models?
For most of CakePHP's model functions you don't have to worry about escaping the input.
CakePHP already protects you against SQL Injection if you use:
- CakePHP's ORM methods (such as
find()
andsave()
) plus:- 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.
See https://book.cakephp.org/2.0/en/core-utility-libraries/sanitize.html There are other cases, however, when you need to run a custom SQL query or subquery. In these cases you can either:
Use Prepared Statements
$db->fetchAll(
'SELECT * from users where username = :username AND password = :password',
['username' => 'jhon','password' => '12345']
);
Custom Escaping with Model->getDataSource()->value()
$sql = 'SELECT * FROM table WHERE name = '
. $this->MyModel->getDataSource()->value($untrustedInput, 'string') . ';'
The value()
function basically escapes and adds quotes like this:
"'" . mysql_real_escape_string($data, $this->MyModel->getDataSource()->connection) . "'"
Sanitize Class
This used to be an option, but was deprecated as of CakePHP 2.4.
$name = "somename";
$db = $this->getDataSource();
$this->Model->query('SELECT * FROM models WHERE name = '.$db->value($name, 'string') . ';');
CakePHP cares also about quoting your input, because it is marked as a string.
SELECT * FROM models WHERE name = "somename";
Here's an alternative way of doing things, using Sanitize::paranoid:
http://www.ibm.com/developerworks/opensource/library/os-php-cake3/
精彩评论