Clean input from the form

I am not sure I am understanding why this function doesnt clean data that it is given. As an example I have php script that looks something like this…

<?php
   
   if (isset($_GET["my_submit"])) {
      $cost = htmlspecialchars($_GET["cost"]);
      echo $cost;
   }
   else {
      $cost = "";
    
   }

when I enter this data <a href='test'>Test</a> into the form I get exactly same in the output.
This is what I see on the screen <a href='test'>Test</a>

Should I not see this output &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;

If you do a ‘view source’ of the output in your browser, you will see the html entities.

htmlspecialchars() is an OUTPUT function. You use it when you output dynamic values on a web page. You do NOT use it on input data that you are going to use in your server-side code.

The only alteration you make to input data that you are going to use in your server-side code is to trim() it, so that you can detect if all white-space characters were entered. Anything else changes the meaning of the data. After you trim the value, you should validate that the data is what you expect. If the data is valid, use it. If it is not valid, setup and display a message for the visitor telling them what was wrong with the submitted data.

1 Like

PHP has a filter_var function specifically designed to filter, sanitize and validate input data. As mentioned previously, htmlspecialchars is for output.

The filter_var function supports a number of different filters. In particular the FILTER_SANITIZE_SPECIAL_CHARS probably is close to what you want.

1 Like

That make sense. Thank you

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