2

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?

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304

4 Answers4

2

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:

&lt;b&gt;blah&lt;/b&gt;

Which will render in the page as

<b>blah</b>
Jeff Lambert
  • 24,395
  • 4
  • 69
  • 96
2

Echo don't execute PHP code from string. This is impossible and this is not security hole in your code.

newman
  • 2,689
  • 15
  • 23
  • You know, if you read from a database based on a user input, that $test inside the echo can be mess with right? For example, the user types test"; exit; or something like that in the variable, the user can mess up the page right? I hope you understand what I meant. – Fouzy Fostdecile Dec 29 '12 at 05:18
  • There is any way for run PHP code what you load from database - this special function - eval(). All others functions not executed code from string. If user entered exit() in string then echo will print this string as is: "exit();" and not execute it - just print. – newman Dec 29 '12 at 06:00
1

You can use a template engine like Twig for exemple.

Florian Mithieux
  • 503
  • 1
  • 6
  • 15
0

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");
?>
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252