Tuesday, January 17, 2012

Why do you need stripslashes?

I was recently called upon to do an example PHP program. I took a course in it back in 2009, I think, and there are some things I'm a bit fuzzy on. One is when you need to use stripslashes? This blog is an attempt to answer that question.

From

http://php.net/manual/en/function.stripslashes.php

Un-quotes a quoted string.

An example use of stripslashes() is when the PHP directive magic_quotes_gpc is on (it's on by default), and you aren't inserting this data into a place (such as a database) that requires escaping. For example, if you're simply outputting data straight from an HTML form.


This really doesn't clear things up. So, if you get a quotes string - for example 'foo' - you want to end up with foo without the quotes. Then why do they call it stripslashes? Is it because the apostrophes are escaped like so: \', i.e., with a slash? So, does it get rid of the slash *and* the quote?

Ok, here's example 1:



<?php
$str = "Is your name O\'reilly?";

// Outputs: Is your name O'reilly?
echo stripslashes($str);
?>


So, it gets rid of the slash, not the quote. Now the question is, where does the slash come from? I'm assuming it's inserted by a browser, so whatever string it's processing doesn't get mangled.

So, that just leaves the question of why only when your *not* inserting data to a database. And, presumably that's because the string would get mangled if you unescaped it.

Ok, that's it for stripslashes.

No comments:

Post a Comment