2

I have created custom "Contact Us" form. Put Magento default Captcha as well.

On server side i'm using

 if (!$this->_formKeyValidator->validate($this->getRequest())) {
     return $this->resultRedirectFactory->create()->setPath('*/*/');
 }

Provided frontend jQuery necessary validation. For saving data on server side i'm using $model->save() method.

Did i need to provide extra security on post filds like Name, Email, Description or Magento will handle this? Do i need to use addslashes or any core PHP function to secure my application? So user can't hake my site?

5

To secure custom forms, you should take care of the following:

1. Add frontend validation

This will not just help the user entering the data in the right form, but might also prevent standard typing mistakes. There are a lot of validation rules in Magento 2 which you can use per default. See also app/code/Magento/Ui/view/base/web/js/lib/validation/rules.js.

Do not rely on frontend validation only as it can be easily removed/disabled via browser.

Adding a captcha is also great to prevent unwanted/automated entries.

2. Add serverside validation

Check the received data again: Check for max length, only store numbers where you expect numbers etc.

If possible, use blacklists or whitelists for the data you are expecting. This might not be the case for a contact form, but for other use cases.

Referring to your question: Yes, you should take care and validate the data before handling it over to the model to save it.

As Magento 2 comes with Zend Framework, you may use the Zend\Validator classes for this. Here's an example of the e-mail validator class: https://framework.zend.com/manual/2.4/en/modules/zend.validator.email-address.html

3. Output: Escape the data

Do not store escaped data, escape it when/where it's needed. In this case during output via e-mail or if you show the contact form requests in the backend.

Further information

You might also be interested in this presentation: Secure Input and Output Handling

  • I'm more concerned about Description field, because there i'm using WYIWYG editor. – Ankit Shah Sep 6 '16 at 8:41
  • Oh, that's interesting. Isn't it enough to provide a plain text area for a contact form?! If you continue with the WYSIWYG field I would first check how M2 does it in the admin area. Don't know how they do it yet, will have a look too. – Anna Völkl Sep 6 '16 at 8:48
  • I have to use that as it's requirement @Anna Völkl – Ankit Shah Sep 6 '16 at 8:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.