I have created a custom text field on my checkout page and want to store the data the customer enters into my database. However, do I need to be worried about SQL injection, or any other type of hack / dirty data which might corrupt/hack my database? Do I need to write some code to sanitise the data before inserting it into the Database, or is this taken care of by Magento when passing it to the resource model?
2 Answers
Please make sure you validate the data as good as possible from frontend side but also from server side. Depending on what input you expect you can limit characters, check for wanted/unwanted input, check for allowed values etc.
Whenever you output this custom text, especially in admin area, make sure to escape it. See here: http://devdocs.magento.com/guides/v2.2/frontend-dev-guide/templates/template-security.html
You might as well be interested in my presentation on Secure input and output handling.
- It's going to be a textarea for the user to add additional information. I'm going to limit the char length and would like to make sure they're not adding any JS or other code. What other rule from rules.js would you recommend I use for the frontend? Also, before saving the data in the DB, should I utilise the validation mehtods in \Magento\Eav\Model\Attribute\Data\AbstractData? Thank you!MikeMason– MikeMason2017-11-16 16:36:01 +00:00Commented Nov 16, 2017 at 16:36
- Also, great presentation!MikeMason– MikeMason2017-11-16 16:46:17 +00:00Commented Nov 16, 2017 at 16:46
- 1Hi @MikeMason, if it's a text field, maybe a alphanumeric check could make sense but that maybe will not allow enough. If you want to apply additional filters, have a look at the Zend\Validator classes, for example Zend\Validator\StringLength, see here: framework.zend.com/manual/2.1/en/modules/…Anna Völkl– Anna Völkl2017-11-17 05:58:20 +00:00Commented Nov 17, 2017 at 5:58
- Many thanks for your suggestions. I had a look at the Zend Validator; looks interesting. To see how this has been implemented by Magento2, I had search through the code for examples, but I didn't seem to find it being used anywhere. Does M2 not use the Zend Validator for it's own input validation?MikeMason– MikeMason2017-11-17 09:45:22 +00:00Commented Nov 17, 2017 at 9:45
If you are inserting data using the Magento Model, it will sanitise automatically all the data for you. But if you are inserting raw SQL queries, you need to manually sanitise user inputs to prevent SQL injection.