By default Cakephp will protect app 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. But this does not potect you from XSS attacks.

To Understand XSS attack, i will show a simple example. Create a php code where it will show user posted data. Like this
<?php
if(isset($_POST['msg']) and $_POST['msg']!='')
{
echo $_POST['msg'];
}
?>
<form action="" method="post">
<input type="text" name="msg" />
<input type="submit" value="submit" />
</form>
Now when adding a comment put the following code
[sourcecode language=”javascript”]
<script type=’text/javascript’>top.location.href="google.com"</script>
Now it will go to google.com.
luckily CakePHP has something that is pretty strong for these type of attacks. The hero is App::import(‘Sanitize’). You can sanitize not only a string but a array with clean function. As book said “This function is an industrial-strength, multi-purpose cleaner, meant to be used on entire arrays (like $this->data, for example). The function takes an array (or string) and returns the clean version.” . So import it in app_controller.php. then try it in you code.
$this->data = Sanitize::clean($this->data, array('dollar' => true, 'carriage'=>true,'encode' => true, 'remove_html'=>true));
There is one draw back using the shown code here you have to use html_entity_decode.
<?php echo html_entity_decode($text['Test']['title'])?>
View my other CakePHP tutorial here.
2 replies on “Prevent CakePHP App From XSS Attacks”
Really! Prevent Cake PHP App from XSS attacks
Hiam using cakephp 1.3 , but it doesn’t seem to be wkiorng for me..Any pointer?does these script included in default.ctp doesn’t support to cakephp 1.3? OR am i missing something important which has not been mentioned here..?please suggest..ThanksPavanesh