How to do xss filtering in cakephp 3?

Cakephp version I’m using is 3.4.x

I have more than a dozen forms in my cakephp 3 application. I wanna implement xss filtering for all forms. What’s the easiest way to do this without making changes to all form functions.

I read in one answer that, to sanitize in a view, we should use the CakePHP convenience function h($string) which will render all attempts at XSS completely harmless.

I tried this but id did not work out.

\src\Template\Users\view.ctp

Address: <?= h($user->address) ?>

Is there a way to implement xss filtering before saving data to database?

My Controller function (which cakephp baked for me) for adding a new user and his info

\src\Controller\UsersController.php

public function add(){
    $this->viewBuilder()->setLayout('admin')  ;
    $user = $this->Users->newEntity();
    if ($this->request->is('post')) {
        $user = $this->Users->patchEntity($user, $this->request->getData());
        if ($this->Users->save($user)) {
            $this->Flash->success(__('The user has been saved.'));

            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('The user could not be saved. Please, try again.'));
    }
    $groups = $this->Users->Groups->find('list', ['limit' => 200]);
    $this->set(compact('user', 'groups'));
    $this->set('_serialize', ['user']);
}

\src\Model\Table\UsersTable.php

public function beforeSave(Event $event)
{
    $entity = $event->getData('entity');

    if ($entity->isNew()) {
        $hasher = new DefaultPasswordHasher();

        // Generate an API 'token'
        $entity->api_key_plain = sha1(Text::uuid());

        // Bcrypt the token so BasicAuthenticate can check
        // it during login.
        $entity->api_key = $hasher->hash($entity->api_key_plain);
    }
    return true;
}

Thanks!

The h() function is short for htmlspecialchars(). It will not strip the tags out but convert them to html entities so your browser won’t execute them. They still get displayed. So if in your first screen shot you didn’t see a alert window. It worked.

If you don’t want people to store tags of any kind your can use striptags() before saving. That will remove them completely from the string.