polyhedron
polyhedron

Reputation: 1590

Why does php insert backslash while replacing double quotes

I'm wondering why php adds a backslash when i remove double quotes.

<input type="text" name="number" id="number" />
<input type="button" name="button" id="button" value="Button" />

Say they user enters the value 5-1/2" and i'm passing it to a processing page via jquery's .get method.

$('#button').click(function(){

    $.get('determine.php?number='+$('#number').val(),function(data){
     $('#response').html(data);
    });

});

Here is my processing page.

determine.php

$number = $_GET['number'];

$number = str_replace(array('"', "'"), '', $number);

echo $number;

//echos 5-1/2\

Why is the backslash there?

Upvotes: 3

Views: 5435

Answers (4)

Andy E
Andy E

Reputation: 344733

It doesn't add them when you remove the slash, it automatically escapes them in the query string parameters when the magic_quotes_gpc directive is enabled (and it is, by default pre 5.30). It did this as a security precaution, so that the data could be safely used in a database query. You can disabled them by changing the setting in your php.ini file, see http://www.php.net/manual/en/security.magicquotes.disabling.php.

You can also use stripslashes to remove them:

$number = str_replace(array('"', "'"), '', stripslashes($number));

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.

Upvotes: 8

mellowsoon
mellowsoon

Reputation: 23301

See http://php.net/manual/en/security.magicquotes.php

Magic Quotes is a process that automagically escapes incoming data to the PHP script. It's preferred to code with magic quotes off and to instead escape the data at runtime, as needed.

When on, all ' (single-quote), " (double quote), \ (backslash) and NULL characters are escaped with a backslash automatically.

In short, magic quotes is a feature in PHP where quote characters are automatically escaped with the \ character.

Here are some solutions for turning off magic quotes: http://www.php.net/manual/en/security.magicquotes.disabling.php

Upvotes: 2

Sarfraz
Sarfraz

Reputation: 382861

You possible have bad magic quotes turned on. If that's the case, you should simply disable them from php.ini.

Upvotes: 2

Incognito
Incognito

Reputation: 20785

User input gets escaped by magic quotes.

http://www.php.net/manual/en/function.get-magic-quotes-gpc.php

Elegant weapons for a more... civilized age.

Upvotes: 2

Related Questions