addslashes

(PHP 4, PHP 5)

addslashes — Экранирует спецсимволы в строке

Описание

string addslashes ( string $str )

Возвращает сроку str , в которой перед каждым спецсимволом добавлен обратный слэш (\), например для последующего использования этой строки в запросе к базе данных. Экранируются одиночная кавычка ('), дойная кавычка ("), обратный слэш (\) и NUL (байт NULL).

Функция addslashes() часто применяется при записи в базу данных. Предположим, если нужно внести в базу данных имя O'reilly, то символ ' должен быть экранирован. В большинстве баз данных для этого используется \, строка будет выглядеть как O\'reilly. Заметьте, что сам символ \ в базу данных записан не будет. Если директива конфигурации magic_quotes_sybase имеет значение on, то символ ' будет экранироваться добавлением еще одного ' вместо \.

Директива конфигурации magic_quotes_gpc по умолчанию имеет значение on, при этом функция addslashes() автоматически применяется ко всем данным GET, POST, и COOKIE. Не используйте addslashes() для данных, обработанных magic_quotes_gpc, чтобы избежать двойного экранирования. Для проверки состояния этой директивы используется get_magic_quotes_gpc().

Пример #1 Пример использования addslashes()

<?php
$str 
"Is your name O'reilly?";

// выводит: Is your name O\'reilly?
echo addslashes($str);
?>

См. также описание функций stripslashes(), htmlspecialchars(), quotemeta() и get_magic_quotes_gpc().

Коментарии

Remember to slash underscores (_) and percent signs (%), too, if you're going use the LIKE operator on the variable or you'll get some unexpected results.
2001-05-09 01:46:08
http://php5.kiev.ua/manual/ru/function.addslashes.html
spamdunk at home dot com, your way is dangerous on PostgreSQL (and presumably MySQL). You're quite correct that ANSI SQL specifies using ' to escape, but those databases also support \ for escaping (in violation of the standard, I think). Which means that if they pass in a string that includes a "\'", you expand it to "\'''" (an escaped quote followed by a non-escaped quote. WRONG! Attackers can execute arbitrary SQL to drop your tables, make themselves administrators, whatever they want.)

The best way to be safe and correct is to:

- don't use magic quotes; this approach is bad. For starters, that's making the assumption that you will be using your input in a database query, which is arbitrary. (Why not escape all "<"s with "&lt;"s instead? Cross-site scripting attacks are quite common as well.) It's better to set up a way that does whatever escaping is correct for you when you use it, as below:

- when inserting into the database, use prepared statements with placeholders. For example, when using PEAR DB:

<?php
    $stmt 
$dbh->prepare('update mb_users set password = ? where username = ?');
   
$dbh->execute($stmt, array('12345''bob'));
?>

Notice that there are no quotes around the ?s. It handles that for you automatically. It's guaranteed to be safe for your database. (Just ' on oracle, \ and ' on PostgreSQL, but you don't even have to think about it.)

Plus, if the database supports prepared statements (the soon-to-be-released PostgreSQL 7.3, Oracle, etc), several executes on the same prepare can be faster, since it can reuse the same query plan. If it doesn't (MySQL, etc), this way falls back to quoting code that's specifically written for your database, avoiding the problem I mentioned above.

(Pardon my syntax if it's off. I'm not really a PHP programmer; this is something I know from similar things in Java, Perl, PL/SQL, Python, Visual Basic, etc.)
2002-10-30 12:48:23
http://php5.kiev.ua/manual/ru/function.addslashes.html
Beware of using addslashes() on input to the serialize() function.   serialize() stores strings with their length; the length must match the stored string or unserialize() will fail. 

Such a mismatch can occur if you serialize the result of addslashes() and store it in a database; some databases (definitely including PostgreSQL) automagically strip backslashes from "special" chars in SELECT results, causing the returned string to be shorter than it was when it was serialized.

In other words, do this...

<?php
$string
="O'Reilly";
$ser=serialize($string);    # safe -- won't count the slash
$result=addslashes($ser); 
?>

...and not this...

<?php
$string
="O'Reilly";
$add=addslashes($string);   # RISKY!  -- will count the slash
$result=serialize($add);
?>

In both cases, a backslash will be added after the apostrophe in "O'Reilly"; only in the second case will the backslash be included in the string length as recorded by serialize().

[Note to the maintainers: You may, at your option, want to link this note to serialize() as well as to addslashes().  I'll refrain from doing such cross-posting myself...]
2002-11-12 17:16:25
http://php5.kiev.ua/manual/ru/function.addslashes.html
Note that when using addslashes() on a string that includes cyrillic characters, addslashes() totally mixes up the string, rendering it unusable.
2003-07-12 14:23:18
http://php5.kiev.ua/manual/ru/function.addslashes.html
Автор:
addslashes does NOT make your input safe for use in a database query! It only escapes according to what PHP defines, not what your database driver defines. Any use of this function to escape strings for use in a database is likely an error - mysql_real_escape_string, pg_escape_string, etc, should be used depending on your underlying database as each database has different escaping requirements. In particular, MySQL wants \n, \r and \x1a escaped which addslashes does NOT do. Therefore relying on addslashes is not a good idea at all and may make your code vulnerable to security risks. I really don't see what this function is supposed to do.
2005-04-30 23:23:40
http://php5.kiev.ua/manual/ru/function.addslashes.html
Note, this function wont work with mssql or access queries.
Use the function above (work with arrays too).

function addslashes_mssql($str){
    if (is_array($str)) {
        foreach($str AS $id => $value) {
            $str[$id] = addslashes_mssql($value);
        }
    } else {
        $str = str_replace("'", "''", $str);   
    }
   
    return $str;
}

function stripslashes_mssql($str){
    if (is_array($str)) {
        foreach($str AS $id => $value) {
            $str[$id] = stripslashes_mssql($value);
        }
    } else {
        $str = str_replace("''", "'", $str);   
    }

    return $str;
}
2005-10-31 05:18:50
http://php5.kiev.ua/manual/ru/function.addslashes.html
Автор:
This function is deprecated in PHP 4.0, according to this article:

http://www.newsforge.com/article.pl?sid=06/05/23/2141246

Also, it is worth mentioning that PostgreSQL will soon start to block queries involving escaped single quotes using \ as the escape character, for some cases, which depends on the string's encoding.  The standard way to escape quotes in SQL (not all SQL databases, mind you) is by changing single quotes into two single quotes (e.g, ' ' ' becomes ' '' ' for queries).

You should look into other ways for escaping strings, such as "mysql_real_escape_string" (see the comment below), and other such database specific escape functions.
2006-05-24 15:55:19
http://php5.kiev.ua/manual/ru/function.addslashes.html
Here's an example of a function that prevents double-quoting, I'm surprised noone has put something like this up yet... (also works on arrays)

<?php
function escape_quotes($receive) {
    if (!
is_array($receive))
       
$thearray = array($receive);
    else
       
$thearray $receive;
   
    foreach (
array_keys($thearray) as $string) {
       
$thearray[$string] = addslashes($thearray[$string]);
       
$thearray[$string] = preg_replace("/[\\/]+/","/",$thearray[$string]);
    }
   
    if (!
is_array($receive)) 
        return 
$thearray[0];
    else
        return 
$thearray;
}
?>
2006-08-19 20:36:28
http://php5.kiev.ua/manual/ru/function.addslashes.html
Автор:
What happends when you add addslashes(addslashes($str))? This is not a good thing and it may be fixed:

function checkaddslashes($str){       
    if(strpos(str_replace("\'",""," $str"),"'")!=false)
        return addslashes($str);
    else
        return $str;
}

checkaddslashes("aa'bb");  => aa\'bb
checkaddslashes("aa\'bb"); => aa\'bb
checkaddslashes("\'"); => \'
checkaddslashes("'");  => \'

Hope this will help you
2007-03-02 20:06:08
http://php5.kiev.ua/manual/ru/function.addslashes.html
If you want to add slashes to special symbols that would interfere with a regular expression (i.e., . \ + * ? [ ^ ] $ ( ) { } = ! < > | :), you should use the preg_quote() function.
2007-05-24 22:19:09
http://php5.kiev.ua/manual/ru/function.addslashes.html
Be careful on whether you use double or single quotes when creating the string to be escaped:

$test = 'This is one line\r\nand this is another\r\nand this line has\ta tab';

echo $test;
echo "\r\n\r\n";
echo addslashes($test);

$test = "This is one line\r\nand this is another\r\nand this line has\ta tab";

echo $test;
echo "\r\n\r\n";
echo addslashes($test);
2008-12-11 04:44:40
http://php5.kiev.ua/manual/ru/function.addslashes.html
Автор:
Based on:
Danijel Pticar
05-Aug-2009 05:22
I recommend this extended version, to replace addslashes altogether(works for both strings and arrays):
<?php
function addslashesextended(&$arr_r)
{
    if(
is_array($arr_r))
    {
        foreach (
$arr_r as &$val)
           
is_array($val) ? addslashesextended($val):$val=addslashes($val);
        unset(
$val);
    }
    else
       
$arr_r=addslashes($arr_r);
}
?>
2009-08-25 08:11:17
http://php5.kiev.ua/manual/ru/function.addslashes.html
Never use addslashes function to escape values you are going to send to mysql. use mysql_real_escape_string or pg_escape at least if you are not using prepared queries yet.

keep in mind that single quote is not the only special character that can break your sql query. and quotes are the only thing which addslashes care.
2010-06-18 04:35:07
http://php5.kiev.ua/manual/ru/function.addslashes.html
To output a PHP variable to Javascript, use json_encode().

<?php

$var 
"He said \"Hello O'Reilly\" & disappeared.\nNext line...";
echo 
"alert(".json_encode($var).");\n";

?>

Output:
alert("He said \"Hello O'Reilly\" & disappeared.\nNext line...") ;
2011-02-01 10:45:18
http://php5.kiev.ua/manual/ru/function.addslashes.html
Автор:
Even for simple json string backslash encodings, do not use this function. Some tests may work fine, but in json the single quote (') must not be escaped.
2012-04-03 11:51:32
http://php5.kiev.ua/manual/ru/function.addslashes.html
Автор:
If all you want to do is quote a string as you would normally do in PHP (for example, when returning an Ajax result, inside a json string value, or when building a URL with args), don't use addslashes (you don't want both " and ' escaped at the same time). Instead, just use this function:

<?php
function Quote($Str// Double-quoting only
   
{
   
$Str=str_replace('"','\"',$Str);
    return 
'"'.$Str.'"';
    } 
// Quote
?>

Modify this easily to get a single-quoting function.
2013-10-04 17:30:21
http://php5.kiev.ua/manual/ru/function.addslashes.html
Автор:
For PHP 7.3.* use FILTER_SANITIZE_ADD_SLASHES.

<?php
$str 
"Is your name O'Reilly?";
$strWithSlashes filter_var($strFILTER_SANITIZE_ADD_SLASHES);

// Outputs: Is your name O\'Reilly?
echo $strWithSlashes;

?>
2019-07-19 19:41:10
http://php5.kiev.ua/manual/ru/function.addslashes.html
escape '$'  using backslash '\$'

<?php

  $evalStr 
"5 + 3";
 
$sum 0
 
$evalStr " \$sum = "$evalStr.";"
  eval( 
$evalStr);
  print (
"sum ".$sum);

?>
2020-08-12 06:22:30
http://php5.kiev.ua/manual/ru/function.addslashes.html
Addslashes is *never* the right answer, it's (ab)use can lead to security exploits!

if you need to escape HTML, it's (unfortunately)
<?php
echo htmlentities($htmlENT_QUOTES|ENT_SUBSTITUTE|ENT_DISALLOWED);
?>
if you need to quote shell arguments, it's
<?php
$cmd
.= " --file=" escapeshellarg($arg);
?>
if you need to quote SQL strings it's
<?php
$sql
.= "WHERE col = '".$mysqli->real_escape_string($str)."'";
?>
or
<?php
$sql
.= "WHERE col = " $pdo->quote($str);
?>
if you need to quote javascript/json strings its
<?php
let str 
= <?=json_encode($strJSON_THROW_ON_ERROR);?>;
?>

if you need to quote a string in xpath it's
<?php
//based on https://stackoverflow.com/a/1352556/1067003
function xpath_quote(string $value):string{
    if(
false===strpos($value,'"')){
        return 
'"'.$value.'"';
    }
    if(
false===strpos($value,'\'')){
        return 
'\''.$value.'\'';
    }
   
// if the value contains both single and double quotes, construct an
    // expression that concatenates all non-double-quote substrings with
    // the quotes, e.g.:
    //
    //    concat("'foo'", '"', "bar")
   
$sb='concat(';
   
$substrings=explode('"',$value);
    for(
$i=0;$i<count($substrings);++$i){
       
$needComma=($i>0);
        if(
$substrings[$i]!==''){
            if(
$i>0){
               
$sb.=', ';
            }
           
$sb.='"'.$substrings[$i].'"';
           
$needComma=true;
        }
        if(
$i < (count($substrings) -1)){
            if(
$needComma){
               
$sb.=', ';
            }
           
$sb.="'\"'";
        }
    }
   
$sb.=')';
    return 
$sb;
}
$xp->query('/catalog/items/item[title='.xpath_quote($var).']');
?>
if you need to quote strings in CSS its
<?php
// CSS escape code ripped from Zend Framework ( https://github.com/zendframework/zf2/blob/master/library/Zend/Escaper/Escaper.php )
function css_escape_string($string)
{
   
$cssMatcher = function ($matches) {
       
$chr $matches[0];
        if (
strlen($chr) == 1) {
           
$ord ord($chr);
        } else {
           
$chr mb_convert_encoding($chr'UTF-16BE''UTF-8'); // $this->convertEncoding($chr, 'UTF-16BE', 'UTF-8');
           
$ord hexdec(bin2hex($chr));
        }
        return 
sprintf('\\%X '$ord);
    };
   
$originalEncoding mb_detect_encoding($string);
    if (
$originalEncoding === false) {
       
$originalEncoding 'UTF-8';
    }
    ;
   
$string mb_convert_encoding($string'UTF-8'$originalEncoding); // $this->toUtf8($string);
                                                                        // throw new Exception('mb_convert_encoding(\''.$string.'\',\'UTF-8\',\''.$originalEncoding.'\');');
   
if ($string === '' || ctype_digit($string)) {
        return 
$string;
    }
   
$result preg_replace_callback('/[^a-z0-9]/iSu'/*$this->*/$cssMatcher$string);
   
// var_dump($result);
   
return mb_convert_encoding($result$originalEncoding'UTF-8'); // $this->fromUtf8($result);
}

?>

- but never addslashes.
2022-03-02 18:08:00
http://php5.kiev.ua/manual/ru/function.addslashes.html

    Поддержать сайт на родительском проекте КГБ