Increasing understanding of validating a string with PHP string functions

Posted by user1554264 on Stack Overflow See other posts from Stack Overflow or by user1554264
Published on 2014-05-29T15:04:02Z Indexed on 2014/05/29 15:27 UTC
Read the original article Hit count: 182

Filed under:

I've just started attempts to validate data in PHP and I'm trying to understand this concept better. I was expecting the string passed as an argument to the $data parameter for the test_input() function to be formatted by the following PHP functions.

  1. trim() to remove white space from the end of the string
  2. stripslashes() to return a string with backslashes stripped off
  3. htmlspecialchars() to convert special characters to HTML entities

The issue is that the string that I am echoing at the end of the function is not being formatted in the way I desire at all. In fact it looks exactly the same when I run this code on my server - no white space removed, the backslash is not stripped and no special characters converted to HTML entities.

My question is have I gone about this in the wrong approach? Should I be creating the variable called $santised_input on 3 separate lines with each of the functions trim(), stripslashes() and htmlspecialchars()?

By my understanding surely I am overwriting the value of the $santised_input variable each time I recreate it on a new line of code. Therefore the trim() and stripslashes() string functions will never be executed.

What I am trying to achieve is using the "$santised_input" variable to run all of these PHP string functions when the $data argument is passed to my test_input() function. In other words can these string functions be chained together so that I only need to create $santised_input once?

<?php

function test_input($data) {
   $santised_input = trim($data);
   $santised_input = stripslashes($data);
   $santised_input = htmlspecialchars($data);
   echo $santised_input;
}

test_input("%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E\     ");

//Does not output desired result "&quot;&gt;&lt;script&gt;alert('hacked')&lt;/script&gt;"

?>

© Stack Overflow or respective owner

Related posts about php