mowwwalker
mowwwalker

Reputation: 17392

PHP submitting forms, escaped quotes?

If I have a form with a value of just "" and I submit it and echo it with PHP, I get \"\"

How can I get around this?

Upvotes: 3

Views: 3219

Answers (5)

Ben Potter
Ben Potter

Reputation: 875

I always use this method as it grabs the value as a string and therefore there will be no slashes:

$variable = mysql_escape_string($_REQUEST['name_input']);

Upvotes: 0

Tomas
Tomas

Reputation: 59575

You should switch off magic_quotes_gpc, which is a broken feature (see Delan's answer, I completely agree).

But wait! You must sanitize the user input from $_REQUEST, $_POST and $_GET and $_COOKIE, if you want to use it for database or display at your page! Otherwise your code would be prone to various types of attacks!

There is nothing like "universal sanitization". Let's call it just quoting, because that's what its all about.

When quoting, you always quote text for some particular output, like:

  1. string value for mysql query
  2. like expression for mysql query
  3. html code
  4. json
  5. mysql regular expression
  6. php regular expression

For each case, you need different quoting, because each usage is present within different syntax context. This also implies that the quoting shouldn't be made at the input into PHP, but at the particular output! Which is the reason why features like magic_quotes_gpc are broken (always assure it is switched off!!!).

So, what methods would one use for quoting in these particular cases? (Feel free to correct me, there might be more modern methods, but these are working for me)

  1. mysql_real_escape_string($str)
  2. mysql_real_escape_string(addcslashes($str, "%_"))
  3. htmlspecialchars($str)
  4. json_encode() - only for utf8! I use my function for iso-8859-2
  5. mysql_real_escape_string(addcslashes($str, '^.[]$()|*+?{}')) - you cannot use preg_quote in this case because backslash would be escaped two times!
  6. preg_quote()

Upvotes: 2

stewe
stewe

Reputation: 42654

You can use stripslashes() function. http://php.net/manual/en/function.stripslashes.php

This behavior is caused by the "Magic Quotes" PHP-Feature. http://php.net/manual/en/security.magicquotes.php

You can use something like this to make it work whether magic quotes are enabled or not:

if (get_magic_quotes_gpc()) {
    $data = stripslashes($_POST['data']);
}
else {
    $data = $_POST['data'];
}

Upvotes: 1

Delan Azabani
Delan Azabani

Reputation: 81482

This is because magic_quotes_gpc is on. This is a bad 'feature', designed to automatically escape incoming data for those developers who can't learn to escape SQL input.

You should disable this as soon as possible.

ini_set('magic_quotes_gpc', 'off');

Upvotes: 5

TeamBlast
TeamBlast

Reputation: 438

Try stripslashes(). stripslashes() is the opposite of addslashes(), and removes escape slashes from strings.

Upvotes: 1

Related Questions