Search code examples
phpstripslashesaddslashes

Not able to remove backslash from below code?


below is my code the issue is that when i enter any username with apostrophe (') Additional character "\ backslash" is being displayed when Search results are returned.

Below is my code i find that a function addslashes is used in the checkusername function so backslash is getting added.

if ( 0 < count( $my_field_place ))
    {
        for ( $i = 0; $i < count( $my_field_place ); $i++ )
        {
            if ( true === isset( $Fields[$i] ))
            {
                print "gMapping[$i] = new MappingItem( '" .
                        addslashes( $Fields[$i] ) .
                        "', '" .
                        checkusername( $my_field_place[$i] ) .
                        "' );";
            }
        }
    }


function checkusername($inStr)
{
  $orig = array();
  $new  = array();

  $orig[00] = "/\n/`"          ;  $new[00] = "\\?n";
  $orig[01] = "/[^\x-*()]/";  $new[01] = "";

  $var1 = preg_replace($orig, $new, $inStr);
  $var2 = addslashes($var1 );     // i am not sure why addslashes is used but i am asked not to remove because of security reasion?                        

  return $var2;
}

Note: I google and find that it used for security reason Since in my case we are only displaying the searched result. So i am not sure why this function is used here. My fix is to add stripslashes() function before returning which will removes backslashes added by the addslashes() function. Please find the code snippet and the comment for code change below:

function checkusername($inStr)
{
  $orig = array();
  $new  = array();

  $orig[00] = "/\n/`"          ;  $new[00] = "\\?n";
  $orig[01] = "/[^\x-*()]/";  $new[01] = "";

  $var1 = preg_replace($orig, $new, $inStr);
  $var2 = addslashes($var1);                           

  return stripslashes($var2); // i am not sure stripslashes is correct fix or not?
}

Please help is it fine to added stripslashes or is there any other way to handle it ?


Solution

  • You can restrict user from those special characeter though in gmail ,yahoo,fb etc they will never allow this character.since t allows multiple words to be represented in a somewhat readable manner below are some doc https://support.google.com/a/answer/33386?hl=en see second guidelines