Magento 1.9 PHP – Function of echo $this->escapeHtml($this->getUsername())

magento-1.9PHP

I have the below piece of code

        <ul class="form-list">
                <li>
                    <label for="login-email" class="required"><em>*</em><?php echo $this->__('Email Address') ?></label>
                    <div class="input-box">
                        <input type="text" class="input-text required-entry validate-email" id="login-email" name="login[username]" value="<?php echo $this->escapeHtml($this->getUsername()) ?>" />
                    </div>
                </li>
                <li>
                    <label for="login-password" class="required"><em>*</em><?php echo $this->__('Password') ?></label>
                    <div class="input-box">
                        <input type="password" class="input-text required-entry" id="login-password" name="login[password]" />
                    </div>
                </li>
                <?php echo $this->getChildHtml('form.additional.info'); ?>
            </ul>

While most of the above are clear, I am struggling to understand the use of the below line

   <?php echo $this->escapeHtml($this->getUsername()) ?>

Why couldn't I have just done

  <?php echo $this->getUsername()?>

If it is a blank form that is seeking input, then what is being echoed?

Thanks for the help

Best Answer

Mage_Core_Model_Abstract::escapeHtml($data) is used to convert special characters to HTML entities from the passing data. That means it is used to avoid cross-site scripting (XSS) via special characters

The code $this->escapeHtml($this->getUserName()) is equivalent to

 htmlspecialchars($this->getUserName(), ENT_COMPAT, 'UTF-8', false);

This is needed here because, when you have submitted the login form with wrong credentials, then Magento will populate the username field with previous POSTed username. But also it makes sure, there is no special characters present in the username field by enclosing user_name in escapeHtml() function.

There are also similar functions available in Mage_Core_Helper_Abstract and in Mage_Core_Model_Abstract classes. It will worth if you have a look over there. If you are lazy, then go through this.

Related Topic