Jump to content

Sanitization of php forms


Recommended Posts

Hi. I have a doubt with the proper way of sanitize the forms with php. In the php form validation lesson https://www.w3schools.com/php/php_form_validation.asp is used a function for this purpose:


function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;

But in the filters lesson, https://www.w3schools.com/php/php_filter.asp I understand that filters can do the same task. Is this correct? Are two approaches valid? Which one should be used nowadays?

Thanks in advance!

Edited by oxk4r
fix code
Link to comment
Share on other sites

You should use filter_input.  That test_input function has several problems.  First, you might not always want to do that to the data, trim it, convert special HTML characters, etc.  Second, that function does not test anything, so they didn't even name it correctly.  It's an old way of handling data that only works in one specific instance.  The filter_input and filter_var functions are general-purpose functions.  After you get the data then you need to handle it appropriately based on what you're going to do with it.  If you're going to print it, for example, you may want to strip HTML code out of it, convert characters, or whatever else to protect against XSS attacks on your site.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...