I have a webpage and I realized that I am showing all variables with "{!!". I recently discovered that is not the same that double bracket "{{".
{!! is not secure because it can for example execute an script but there are situations where I need to use it.
If I store this <p style="color:red;">hello<p>
in a php variable and then I want to show it, how could I do it securely? I want the user see "hello" in red, not the html tags.
EDIT: You say me in comments that user shouldn't be able to write html. Ok but if the user write on a textarea and he introduce new lines or carriage returns how can I show them later? I can use the nl2br()
function of php but to make <br>
visible I must user {!! !!}. I suppose that there is a secure way to do it in that cases.
This is really a question of levels of trust: you trust your users to write some HTML, e.g. formatting, but don't trust them to write all HTML, e.g. script insertions.
So firstly, you need to define exactly what HTML you want to allow, as a strict whitelist. Remember that you need to whitelist attributes as well as tags, so users can't write <p style="text-decoration: underline;" onclick="evil();">hello<p>
.
Ideally, this whitelist should be enforced when the HTML is entered into your system: if the user enters invalid HTML, it should be stripped immediately, or the input rejected with an appropriate message.
You could alternatively do it on retrieval, or even on display using a custom function in your templates, but this creates a risk that you (or someone else working on the code) will forget to pass some content through this mechanism, and display HTML which should have been restricted.