Function to Sanitize Input - am I on the right line?

Hi Folks, this is my first post here, I’ve had a look around and I’m not sure how to find out what I’m looking for, so I thought I’d write a post.

I have been doing a lot of reading lately about PHP and MySQL security, and how to stop injections and what not. I’m aware of the concepts of what needs to be done, but not the real meat and bones procedure behind it.

My own take on how to make my form inputs safer, was to write a php function like this:

function sanitizeInput($string)
	$sanitized_string = str_replace(";","& #59 ;",$string);
	$sanitized_string = str_replace("*","& #42 ;",$sanitized_string);
	$sanitized_string = str_replace("-","& #45 ;",$sanitized_string);
	$sanitized_string = str_replace("'","& #39 ;",$sanitized_string);
	$sanitized_string = str_replace("\\"","& #34 ;",$sanitized_string);
	$sanitized_string = str_replace(",","& #44 ;",$sanitized_string);
	$sanitized_string = str_replace("(","& #40 ;",$sanitized_string);
	$sanitized_string = str_replace(")","& #41 ;",$sanitized_string);
	return $sanitized_string;

(I’ve added spaces to the html codes because whenever I type them in here properly, my browser displays them as the actual characters, not the html codes)

I know that the addslashes and stripslashes command are supposed to be involved too, but I figured that maybe this is a safe extra layer of security?

Is my function completely pointless? Are there better methods to do what I want to do?

Thanks in advance for any feedback.

Skip mysql_real_escape_string().

What you’re looking for is the PHP filter_var() function. It’s not database specific, it protects against more than just SQL injection, and it’s faster because it’s part of the core language. Manual page here:

Make sure to check out the link on that page called “types of filters” which should give you some ideas on what exactly can be accomplished. Needless to see, it’s a much more well-rounded solution than simply escaping.

Hah, thanks for your input! Most of the articles I’ve been reading just say “don’t fall into these pitfalls!” without much info about how. Even a quick “Check out mysql_real_escape_string” would’ve set me in the right direction.

No need to rewrite an algorithm when mysql_real_escape_string function is available. It will sanitize all user input for you.

To sanitize HTML use htmlentities function.


Your logic is off in your function.

What if a user wrote a sentence:

I was going to go to the park, but then my girlfriend (which I’m still in a fight with her about this) said we couldn’t go because we needed to go to a wedding rehearsal.

You would replace all the delimiters and it wouldn’t emphasizes.