PHP Doku:: Entfernt aus einem gequoteten String alle Quotes - function.stripslashes.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzTextverarbeitungZeichenkettenString-Funktionenstripslashes

Ein Service von Reinhard Neidl - Webprogrammierung.

String-Funktionen

<<stripos

stristr>>

stripslashes

(PHP 4, PHP 5)

stripslashesEntfernt aus einem gequoteten String alle Quotes

Beschreibung

string stripslashes ( string $str )

Entfernt aus einem gequoteten String alle Quotes.

Hinweis:

Wenn magic_quotes_sybase eingeschaltet ist, werden keine einfachen Backslashes entfernt, doppelte jedoch durch einfache Backslashes ersetzt.

Eine exemplarische Anwendung für stripslashes() ergibt sich, wenn die PHP-Direktive magic_quotes_gpc auf On gesetzt ist (Default-Einstellung), und Sie die übermittelten Daten an anderer Stelle, die eigenes Escaping erfordert (wie z.B. eine Datenbank), einfügen wollen. Zum Beispiel, wenn Sie Daten direkt aus einem HTML-Formular verarbeiten wollen.

Parameter-Liste

str

Die Eingabezeichenkette.

Rückgabewerte

Gibt einen String zurück, aus dem alle Backslashes ("\") entfernt wurden. (\' wird zu ' usw.). Doppelte Rückstriche (\\) werden zu einem einfachen Backslash (\) umgesetzt.

Beispiele

Beispiel #1 Ein stripslashes()-Beispiel

<?php
$str 
"Ist Ihr Name O\'reilly?";

// Ausgabe: Ist Ihr Name O'reilly?
echo stripslashes($str);
?>

Hinweis:

stripslashes() ist nicht rekursiv. Wenn Sie die Funktion auf ein mehrdimensionales Array anwenden wollen, müssen Sie eine rekursive Funktion verwenden.

Beispiel #2 Verwendung von stripslashes() in einem Array

<?php
function stripslashes_deep($value)
{
    
$value is_array($value) ?
                
array_map('stripslashes_deep'$value) :
                
stripslashes($value);

    return 
$value;
}

// Beispiel
$array = array("f\\'oo""b\\'ar", array("fo\\'o""b\\'ar"));
$array stripslashes_deep($array);

// Ausgabe
print_r($array);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Array
(
    [0] => f'oo
    [1] => b'ar
    [2] => Array
        (
            [0] => fo'o
            [1] => b'ar
        )

)

Siehe auch


27 BenutzerBeiträge:
- Beiträge aktualisieren...
jeremysawesome
10.12.2010 21:39
I'm using this to clean the $_POST array:
<?php
array_walk_recursive
($_POST, create_function('&$val', '$val = stripslashes($val);'));
?>
jeremycook0 at googlemail dot com
1.08.2010 17:04
Here's a way of stripping slashes in PHP 5.3 using a recursive closure:

<?php
 
if (get_magic_quotes_gpc()) {
     
$strip_slashes_deep = function ($value) use (&$strip_slashes_deep) {
          return
is_array($value) ? array_map($strip_slashes_deep, $value) : stripslashes($value);
      };
     
$_GET = array_map($strip_slashes_deep, $_GET);
     
$_POST = array_map($strip_slashes_deep, $_POST);
     
$_COOKIE = array_map($strip_slashes_deep, $_COOKIE);
  }
?>

Note that the variable '$strip_slashes_deep' has to be passed to the closure by reference. I think that this is because at the time the closure is created the variable '$strip_slashes_deep' doesn't exist: the closure itself becomes the value of the variable. Passing by reference solves this issue. This closure could easily be adapted to use other methods of stripping slashes such as preg_replace().
hawkeye at conreports dot de
21.01.2010 14:01
Another way to strip slashes only if necessary, independent of magic_quotes_gpc by comparing the count of (possibly) escaped characters and original characters.

<?php
function smartstripslashes($str) {
 
$cd1 = substr_count($str, "\"");
 
$cd2 = substr_count($str, "\\\"");
 
$cs1 = substr_count($str, "'");
 
$cs2 = substr_count($str, "\\'");
 
$tmp = strtr($str, array("\\\"" => "", "\\'" => ""));
 
$cb1 = substr_count($tmp, "\\");
 
$cb2 = substr_count($tmp, "\\\\");
  if (
$cd1 == $cd2 && $cs1 == $cs2 && $cb1 == 2 * $cb2) {
    return
strtr($str, array("\\\"" => "\"", "\\'" => "'", "\\\\" => "\\"));
  }
  return
$str;
}
?>
eugene at ultimatecms dot co dot za
23.11.2009 14:03
This is a simple function to remove the slashes added by functions such as magic_quotes_gpc and mysql_escape_string etc.

<?php

function no_magic_quotes($query) {
       
$data = explode("\\",$query);
       
$cleaned = implode("",$data);
        return
$cleaned;
}

// I'm using mysql_escape_string as a simple example, but this function would work for any escaped string.
$query = "It's amaizing! Who's to say this isn't a simple function?";
$badstring = mysql_escape_string($query);

echo
'<b>Without funtion:</b> '.$badstring;
echo
'<br><br>';
echo
'<b>With function:</b> '.no_magic_quotes($badstring);

?>

Output:
Without funtion: It\'s amaizing! Who\'s to say this isn\'t a simple function?

With function: It's amaizing! Who's to say this isn't a simple function?
michal at roszka dot pl
1.09.2009 5:00
The goal is to leave the input untouched in PHP 5.2.8. Let's have this sample text given in $_POST['example']:

a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )

Let's have two simple scripts:

Script A:
<?php echo $_POST['example']; ?>

Script B:
<?php echo stripslashes($_POST['example']); ?>

Let's have four different configurations and corresponding output:

Case #1:

 * magic_quotes_gpc = Off
 * magic_quotes_sybase = Off

A: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )
B: a backslash (  ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )

Case #2

 * magic_quotes_gpc = On
 * magic_quotes_sybase = Off

A: a backslash ( \\ ), a single-quote ( \' ), a double-quote ( \" ) and a null character ( \\0 )
B: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )

Case #3

 * magic_quotes_gpc = On
 * magic_quotes_sybase = On
 
A: a backslash ( \ ), a single-quote ( '' ), a double-quote ( " ) and a null character ( \0 )
B: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )

Case #4

 * magic_quotes_gpc = Off
 * magic_quotes_sybase = On

A: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )
B: a backslash (  ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )

Conclusions:

1) we do not need to do anything, if the magic_quotes_gpc is disabled (cases 1 and 4);
2) stripslashes($_POST['example']) only works, if the magic_quotes_gpc is enabled, but the magic_quotes_sybase is disabled (case 2);
3) str_replace("''", "'", $_POST['example']) will do the trick if both the magic_quotes_gpc and the magic_quotes_sybase are enabled (case 3);

<?php
function disable_magic_quotes_gpc()
{
    if (
TRUE == function_exists('get_magic_quotes_gpc') && 1 == get_magic_quotes_gpc())
    {
       
$mqs = strtolower(ini_get('magic_quotes_sybase'));

        if (
TRUE == empty($mqs) || 'off' == $mqs)
        {
           
// we need to do stripslashes on $_GET, $_POST and $_COOKIE
       
}
        else
        {
           
// we need to do str_replace("''", "'", ...) on $_GET, $_POST, $_COOKIE
       
}
    }
   
// otherwise we do not need to do anything
}
?>

Important notes:

1) arrays need to be processed recursively;

2) both stripslashes and str_replace functions always return strings, so:

* TRUE will become a string "1",
* FALSE will become an empty string,
* integers and floats will become strings,
* NULL will become an empty string.

On the other hand you only need to process strings, so use the is_string function to check;

3) when dealing with other (than GPC) data sources, such as databases or text files, remember to play with the magic_quotes_runtime setting as well, see, what happens and write a corresponding function, i.e. disable_magic_quotes_runtime() or something.

4) VERY IMPORTANT: when testing, remember the null character. Otherwise your tests will be inconclusive and you may end up with... well, serious bugs :)
JacobRas.nl
28.07.2009 14:41
Hi,

Here's an function that strips not only \', but also \\' and \\\' and so on (depending on $times). $text = the text that needs to be stripped, $times = how much backslashes should be stripped.

<?php

function stripslashes_deep ($text, $times) {
   
   
$i = 0;
   
   
// loop will execute $times times.
   
while (strstr($text, '\\') && $i != $times) {
       
       
$text= stripslashes($text);
       
$i++;
       
    }
   
    return
$text;
   
}

?>

Example: $text = \\'quote\\' . <?php stripslashes_deep($text, 2); ?> will return 'quote'.
Note: <?php stripslashes_deep($text, 3); ?> will also return 'quote'.
shredder at technodrome dot com
10.05.2009 0:50
Hi,

Here are recursive addslashes / stripslashes functions.
given a string - it will simply add / strip slashes
given an array - it will recursively add / strip slashes from the array and all of it subarrays.
if the value is not a string or array - it will remain unmodified!

<?php

function add_slashes_recursive( $variable )
{
    if (
is_string( $variable ) )
        return
addslashes( $variable ) ;

    elseif (
is_array( $variable ) )
        foreach(
$variable as $i => $value )
           
$variable[ $i ] = add_slashes_recursive( $value ) ;

    return
$variable ;
}

function
strip_slashes_recursive( $variable )
{
    if (
is_string( $variable ) )
        return
stripslashes( $variable ) ;
    if (
is_array( $variable ) )
        foreach(
$variable as $i => $value )
           
$variable[ $i ] = strip_slashes_recursive( $value ) ;
   
    return
$variable ;
}

?>
dragon[dot]dionysius[at]gmail[dot]com
24.03.2009 17:07
I use this function in my class to stripslashes arrays including NULL-check:

<?php
   
private function stripslashes_deep($value) {
        if(
is_array($value)) {
            foreach(
$value as $k => $v) {
               
$return[$k] = $this->stripslashes_deep($v);
            }
        } elseif(isset(
$value)) {
           
$return = stripslashes($value);
        }
        return
$return;
    }
?>
Tom Worster
23.03.2009 16:26
A replacement that should be safe on utf-8 strings.
<?php
  preg_replace
(array('/\x5C(?!\x5C)/u', '/\x5C\x5C/u'), array('','\\'), $s);
?>
o-zone at zerozone dot it
19.03.2009 12:53
If you need to remove all slashes from a string, here's a quick hack:

<?php
function stripallslashes($string) {
    while(
strchr($string,'\\')) {
       
$string = stripslashes($string);
    }
}
?>

Hope it's usefull , O-Zone
techdesk100
28.04.2008 16:58
Function which checks if $input has correct slashes,
otherwise adds slashes. For cases when you are not sure the input is not already addslashed.

    public function addslashes_once($input){
        //These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).
        $pattern = array("\\'", "\\\"", "\\\\", "\\0");
        $replace = array("", "", "", "");
        if(preg_match("/[\\\\'\"\\0]/", str_replace($pattern, $replace, $input))){
            return addslashes($input);
        }
        else{
            return $input;
        }
    }
Aditya P Bhatt (adityabhai at gmail dot com)
28.03.2008 7:03
Here is simple example code which you can use as a common function in your functions file:

<?php
function stripslashes_if_gpc_magic_quotes( $string ) {
    if(
get_magic_quotes_gpc()) {
        return
stripslashes($string);
    } else {
        return
$string;
    }
}
?>
Evgeny
26.02.2008 16:52
extended version of stripslashes_deep. This allow to strip one also in the array_keys

    function stripslashes_deep($value) {
        if (is_array($value)) {
            if (count($value)>0) {
                $return = array_combine(array_map('stripslashes_deep', array_keys($value)),array_map('stripslashes_deep', array_values($value)));
            } else {
                $return = array_map('stripslashes_deep', $value);
            }
            return $return;
        } else {
            $return = stripslashes($value);
            return $return ;
        }
    }
tokyoahead
11.01.2008 6:39
I am using this here to clear data in a CMS against SQL injections and other mayhem. The flow is:

1. input into form
2. get from $_GET/$_POST
3. cleanup($data, true)
4. save to SQL
5. load from SQL
6. cleanup($data, false)
7. show in form for new edit or on the website

<?php
function cleanup($data, $write=false) {
    if (
is_array($data)) {
        foreach (
$data as $key => $value) {
           
$data[$key] = cleanup_lvl2($value, $write);
        }
    } else {
       
$data = cleanup_lvl2($data, $write);
    }
    return
$data;
}

function
cleanup_lvl2($data, $write=false) {
    if (isset(
$data)) { // preserve NULL
       
if (get_magic_quotes_gpc()) {
           
$data = stripslashes($data);
        }
        if (
$write) {
           
$data = mysql_real_escape_string($data);
        }
    }
    return
$data;
}
?>
alex dot launi at gmail dot com
21.12.2007 16:16
kibby: I modified the stripslashes_deep() function so that I could use it on NULL values.

function stripslashes_deep($value)
{
    if(isset($value)) {
        $value = is_array($value) ?
            array_map('stripslashes_deep', $value) :
            stripslashes($value);
    }
    return $value;
}
lukas.skowronski at gmail dot com
20.06.2007 13:15
If You want to delete all slashes from any table try to use my function:

function no_slashes($array)
    {
        foreach($array as $key=>$value)
            {
                if(is_array($value))
                    {
                        $value=no_slashes($value);
                        $array_temp[$key]=$value;                       
                    }
                else
                    {
                        $array_temp[$key]=stripslashes($value);
                    }
            }       
        return $array_temp;   
    }
dragonfly at networkinsight dot net
12.03.2007 0:22
If you are having trouble with stripslashes() corrupting binary data, try using urlencode() and urldecode() instead.
JAB Creations
6.03.2007 5:49
When writing to a flatfile such as an HTML page you'll notice slashes being inserted. When you write to that page it's interesting how to apply stripslashes...

I replaced this line...
<?php fwrite($file, $_POST['textarea']); ?>

With...
<?php if (get_magic_quotes_gpc()) {fwrite ($file, stripslashes($_POST['textarea']));}?>

You have to directly apply stripslashes to $_POST, $_GET, $_REQUEST, and $_COOKIE.
gregory at nutt dot ca
22.02.2007 15:48
Here is code I use to clean the results from a MySQL query using the stripslashes function.

I do it by passing the sql result and the sql columns to the function strip_slashes_mysql_results.  This way, my data is already clean by the time I want to use it.

    function db_query($querystring, $array, $columns)
    {
      if (!$this->connect_to_mysql())
       return 0;

     $queryresult = mysql_query($querystring, $this->link)
        or die("Invalid query: " . mysql_error());
   
      if(mysql_num_rows($queryresult))
      {
          $columns = mysql_field_names ($queryresult);
   
          if($array)
          {
              while($row = mysql_fetch_row($queryresult))
                $row_meta[] = $this->strip_slashes_mysql_results($row, $columns);
              return $row_meta;
          }
          else
          {
              while($row = mysql_fetch_object($queryresult))
                $row_meta[] = $this->strip_slashes_mysql_results($row, $columns);
              return $row_meta;
          }
      }
      else
        return 0;
    }
   
    function strip_slashes_mysql_results($result, $columns)
    {
        foreach($columns as $column)
        {
              if($this->debug)
                  printp(sprintf("strip_slashes_mysql_results: %s",strip_slashes_mysql_results));
              $result->$column = stripslashes($result->$column);
        }
        return $result;
    }
Allen
7.02.2007 8:41
In response to Tim's solution, it is only good for one-dimensional array.  If the variables happened to be multi-dimensional arrays, we still have to use function like 'stripslashes_deep'.
stoic
2.01.2007 17:31
in response to crab dot crab at gmail dot com:

$value need not be passed by reference. The 'stripped' value is returned. The passed value is not altered.
Kibby
14.05.2006 10:41
Okay, if using stripslashes_deep, it will definitely replace any NULL to "".  This will affect to coding that depends isset().  Please provide a workaround based on recent note.
hauser dot j at gmail dot com
21.02.2006 11:13
Don't use stripslashes if you depend on the values NULL.

Apparently stripslashes converts NULL to string(0) ""

<?php
$a
= null;
var_dump($a);

$b = stripslashes($a);
var_dump($b);
?>
Will output

NULL
string(0) ""
alf at mitose dot net
26.10.2005 2:09
Take care using stripslashes() if the text you want to insert in the database contain \n characters ! You'll see "n" instead of (not seeing) "\n".

It should be no problem for XML, but is still boring ...

10.02.2005 16:45
If you want to deal with slashes in double-byte encodings, such as shift_jis or big5, you may use this:

<?
function stripslashes2($string) {
   
$string = str_replace("\\\"", "\"", $string);
   
$string = str_replace("\\'", "'", $string);
   
$string = str_replace("\\\\", "\\", $string);
    return
$string;
}
?>
mattyblah at gmail dot com
10.09.2004 17:51
It should be of note that if you are stripping slashes to get rid of the slashes added by magic_quotes_gpc then it will also remove slashes from \. This may not seem that bad but if you have someone enter text such as 'testing\' with a slash at the end, this will cause an error if not corrected. It's best to strip the slashes, then add a slash to every single slash using $text = str_replace('\\', '\\\\', $text);
hash at samurai dot fm
1.12.2003 6:34
Might I warn readers that they should be vary careful with the use of stripslashes on Japanese text. The shift_jis character set includes a number of two-byte code charcters that contain the hex-value 0x5c (backslash) which will get stripped by this function thus garbling those characters.

What a nightmare!



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)