I have the following question: If I echo a variable, and it contains any type of code (html, php, javascript, etc) will it be executed or will it only be seen as text?
I have this question because I want to make sure that people can't add code in the forms, which will then be displayed on a page.
And well, I am convinced that it can be done with some like JavaScript, so what would be the solution so that the code does not execute?
Thank you very much!
Within a
echo
you can without problem send codehtml
orjavascript
now your form fields should go through a filter before proceeding to execute any action with the data of these, consider that all your users are hackers, always.What could you do ?
Validation with HTML of your Inputs
HTML has evolved quite a bit and one of these evolutions is the validation of form input fields such as a numeric field.
either
Both fields require a valid input, as indicated by the attribute,
type
you can help yourself with this type of validation, although I emphasize that it is not definitive.There is also the attribute
pattern
allows you to run regular expression validations against input values. If, for example, you require passwords to contain at least 1 uppercase character, 1 lowercase character, and 1 number, the browser can validate that for you.You can find much more information in the following link: Validations with HTML
javascript
With javascript there are a lot of solutions, from using
jquery
and its libraries for form validation or usingvanilla javascript
and its powerfulAPI
, this part is quite extensive so I invite you to enter the following link and see for yourself: Validations with JavascriptAnyway I leave you a very basic example;
PHP
Well, we have already entered a field that we can never forget in life and it is the validation in which
backend
it is of the utmost importance not to leave all the validations only to the browser, sayHTML
andJavascript
.The good thing about this is that we have many functions and utilities on our server side, such as:
stripslashes Removes slashes from a string with escaped quotes.
or a case more attached to your question, if a user enters javascript code in an input that you were given to validate;
strip_tags Strips HTML and PHP tags from a string.
More about this in the official documentation: http://php.net/manual/es/function.strip-tags.php
My conclusion
There are many ways to validate and prevent your users from injecting code of any kind, but this would be up to you to consider which ones to use and which ones suit you. The ones I have proposed are not definitive and could contain their faults and cons, but I think leaving the inputs without validating on the client side does not create a good experience.
On the other hand, if you're worried about code injection, you can use the function
strip_tags
to try to remove html and php tags from a text string.You can see the full documentation on php.net