HTML special characters opposite function

I have string that looked like this (which I received from html form)…

$data = "Top Winner"

Which I put trough…

 $d = trim($data); 
 $d = stripslashes($data); 
 $d = htmlspecialchars($data); 

before I put it into the database… result in my database looks like this…

"Top Winner" 

Now I am trying to get this back to “Top Winner” and show it in the browser but it is showing it exactly as it is in the database. I am confused because I tried to use every single function here

PHP Decode

with no success. What am I doing wrong?

What you are doing wrong is not using prepared statements. There is no need for all those code gymnastics to insert data into the DB.

Actually I did use prepared statement “named placeholders” but isn’t it good idea to clean input that you receiving from the forms?

With prepared statements, escaping your data ahead of time is a waste. Just introduces the possibility more of errors. So no stripslashes needed for prepared statements.

The thing you are really missing is that htmlspecialchars is an output function. It takes care of escaping things like <,>,& which might otherwise confuse the browser. It’s very very very seldom to encounter a valid use case for using on input data.

The trim is okay if you need to guard against unwanted leading or trailing spaces.

1 Like

Beat me to it so I will just stand behind your response in agreement to everything you said to op.

In any case

$d = trim($data);
$d = stripslashes($data);
$d = htmlspecialchars($data);

The value of $d is going to be overwritten each time by the next statement.


Ok how should I have done it?

Using prepared statements should guard you against sql injection, though it’s still a good idea to validate the input, I would not encode it on input, as mentioned, trimming is not a bad idea.

What I would do is encode on output:-

<?php echo htmlspecialchars($row['data']); ?>

…to guard against any script injection to your site/app that may slip past the previous validation.

If you were to apply multiple functions on a value (probably not these ones) you must pass the result of the previous function to the next function, not the unchanged original value.
Otherwise, as per your code only the last function will be used, as $data never changes and $d is overwritten on each line.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.