Data Sanitization

Data Sanitization is used to ensure that no malicious code is put into the application.
CakePHP has a sanitize class set up. This core library can be placed anywhere in the application.
App::uses(‘Sanitize’); could have been added to every single controller but by using App::uses(‘Sanitize’, ‘Utility’); in the AppController.php file all controllers will be sanitized.
The code calls the sanitize.php file that is located in app/lib/cake/Utility. Sanitize cleans data that is in a string or an array:
san1

A clean options array should be placed in the AppController.php file:
san2

The clean option:
• replaces odd spaces with regular ones,
• encodes changes any hmtl into entities e.g. < becomes &lt ;.
• the dollar sign is escaped by prepending a \.
• adds \r (carriage return character) which causes a new line in the console but has no effect on web pages,
• replaces unicode with non-unicode,
• escapes using Sanitize::escape (when true).

Controllers for the user input now should be updated. This is done by changing the index function in the CommentsController.php and the PostsController.php:
$this->set('comments', Sanitize::clean($this->paginate(),$this->cleanOptions) ); //ED.
$this->set('posts', Sanitize::clean($this->paginate(),$this->cleanOptions) ); //ED.

san3

To test this solution a comment with 5 spaces between the word in the comment (My _______ spaced comment.) has been created:
san4

And after saving, comment appears it looks like this:
san5