Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Quick question about htmlspecialchars

Hi all,

I'm trying to use htmlspecialchars to escape output, I haven't used this since the shirts4mike project, but on shirts4mike the script for the contact form was something like this:

if ($_POST) {

$name = trim($_POST['name']);

}

//<input type="text" name="name" value="<?php if (isset($name)) { echo htmlspecialchars($name); ?>">

However, when I tried testing htmlspecialchars on my own project, it didn't work. The form values I'm using aren't converted to htmlspecialchars unless I do something like this:

if ($_POST) {
$product_name = htmlspecialchars($_POST['productname']);
}


//<form method="post">
//<input type="text" name="productname" value="<?php if //(isset($product_name)) { echo htmlspecialchars($product_name);} ?>">
//<button type="submit">Go</button>
//</form>

I have to specify htmlspecialchars on the $_POST variable and also again when I output the variable in the form field, why doesn't it work when just escaping it once?

Thanks

1 Answer

What leads you to believe that the htmlspecialchars() is not working? Is there an entity in the product name that is not being translated?

If I type in a script tag for example, after the variable echoes out, it doesn't change it into special chars, and if I inspect the element in the chrome dev tools, it is still the same