I'm quite new here. I'm trying to make a blog/journal site that allows users to post their own journal. I'm still quite reluctant on making it because I am really afraid of malicious code injections.
So here's a sample code:
<?php
$test = "<b>blah</b>"; //User input from SQL
echo "$test";
?>
What will come out is just the word "blah" in bold right? What I was trying to achieve was to echo "<b>blah</b>
" instead. I don't want people to put some PHP codes that can actually mess up my whole web page. Please keep in mind that the variable $test
is actually a MYSQL query, so that variable will be needed as an example. I know you can do echo '$test';
but it just comes out as "$test"
instead. I feel like pulling my hair out I can't figure it out yet.
The second solution I know of is the htmlspecialchars();
function, but I want the strings to display as what I typed, not the converted ones...
Is there any way I can do that?
I think the OP wants the HTML itself to be output to the page, and not have the tags stripped. To achieve this, you can run the string first through htmlentities()
$test = '<b>blah</b>';
echo htmlentities($test);
This will output:
<b>blah</b>
Which will render in the page as
<b>blah</b>
If htmlspecialchars();
is not the one you are looking for, try the header()
option.
header('Content-type: text/plain');
When you are gonna give <b>Hi</b>
to a browser, it will be displayed in Bold and not the text be returned. But you can try this way, outputting it inside a <textarea></textarea>
.
Or the other way is to use htmlentities()
:
<?php
$test = "<b>blah</b>"; //User input from SQL
echo htmlentities("$test");
?>
Echo don't execute PHP code from string. This is impossible and this is not security hole in your code.
You can use a template engine like Twig for exemple.