Search code examples
phpescapingmagic-quotes

PHP keeps escaping my form's input (adding \ behind my ')


So basically when I type something with an apostrophe, such as John's bike it will echo John\'s bike. The code below:

<?php
$searchname = $_POST["name"] ;
echo "$searchname";

My form uses the POST method. Is there any way to stop this?

Also to make input case insensitive how would I go about in this segment?

$searchsport = $_POST['sport'];
$sportarray = array(
"Football" => "Fb01",
"Cricket" => "ck32",
"Tennis" => "Tn43",
);
if(isset($sportarray[$searchsport])){
header("Location: ".$sportarray[$searchsport].".html");
die;
}
    //what code is needed to make the if statement work? I've looked up some weird ways such as using array_change_key_case (which I clearly don't understand).

Solution

  • This is most likely because you have magic quotes turned on, try this:

    if (get_magic_quotes_gpc())
    {
      $searchname = stripslashes($_POST["name"]);
      echo "$searchname";
    }
    else
    {
      $searchname = $_POST["name"];
      echo "$searchname";
    }
    

    In fact, you could create a function instead to do it automatically for you:

    function fixIt($str)
    {
        if (is_array($str))
        {
            foreach ($str as &$value)
            {
                $value = fixIt($value);
            }
    
            return $str;
        }
        else
        {
            return stripslashes($str);
        }    
    }
    

    And then you can simply do:

    $searchname = fixIt($_POST["name"]);
    echo $searchname;
    

    Note: You can also disable the ugly magic quotes from php.ini as they are problematic and rightly deprecated and out of the future versions of PHP.