yii2 - Why use yii\helpers\Html instead of just typing -


just basic newbie question understand reasoning. why should 1 use html helpers available in yii2, or can't type tags if strong in our html skills.

example: seen in basic views...

<h1><?= html::encode($this->title) ?></h1> 

why should not type...

<h1>my title</h1> 

it's you.

but using framework helpers, widgets , coding styles, can keep code consistency, reduce errors, bugs , lower security risks.

using example.

imagine $this->title set name of user in main layout file:

<?php $this->title = $user->name; ?>  <h1><?= $this->title ?></h1> 

now, let's imagine user managed set username <script>console.log('i can steal cookies now!');</script>notahacker in registration form (also because decided save directly database instead of using framework).

that render following:

<h1><script>console.log('i can steal cookies now!');</script>notahacker</h1> 

and see this:

notahacker

and in javascript console appear i can steal cookies now!

that's major security risk! bad people out there can steal cookies information, record activity, steal passwords, etc.

but fixed, using framework way.

<?php $this->title = $user->name; ?>  <h1><?= html::encode($this->title) ?></h1> 

and render:

<h1>&lt;script&gt;console.log(&#39;i can steal cookies now!&#39;);&lt;/script&gt;notahacker</h1> 

and see:

<script>console.log('i can steal cookies now!');</script>notahacker

but nothing executed!

so, what's point? frameworks yii2 develop helpers , widgets can trust them nothing bad happen while use methods (and because if ever come across encoding problems, love helpers classes). crucial in production environment, when have lot of variables , can't let slip through fingers.

tl;dr: if trust framework, use available methods everytime can.


Comments

Popular posts from this blog

javascript - oscilloscope of speaker input stops rendering after a few seconds -

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -