Hướng dẫn escapehtml - thoát html

(PHP 4, PHP 5, PHP 7, PHP 8)

Show

addslashesQuote string with slashes

Description

addslashes(string $string): string

  • single quote (')
  • double quote (")
  • backslash (\)
  • NUL (the NUL byte)

A use case of addslashes() is escaping the aforementioned characters in a string that is to be evaluated by PHP:

$str "O'Reilly?";
eval(
"echo '" addslashes($str) . "';");
?>

The addslashes() is sometimes incorrectly used to try to prevent SQL Injection. Instead, database-specific escaping functions and/or prepared statements should be used.

Parameters

string

The string to be escaped.

Return Values

Returns the escaped string.

Examples

Example #1 An addslashes() example

$str "Is your name O'Reilly?";// Outputs: Is your name O\'Reilly?
echo addslashes($str);
?>

See Also

  • stripcslashes() - Un-quote string quoted with addcslashes
  • stripslashes() - Un-quotes a quoted string
  • addcslashes() - Quote string with slashes in a C style
  • htmlspecialchars() - Convert special characters to HTML entities
  • quotemeta() - Quote meta characters
  • get_magic_quotes_gpc() - Gets the current configuration setting of magic_quotes_gpc

roysimke at microsoftsfirstmailprovider dot com

12 years ago

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.

hoskerr at nukote dot com

19 years ago

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...

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

...and not this...

$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...]

svenr at selfhtml dot org

11 years ago

To output a PHP variable to Javascript, use json_encode().

$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...") ;

geekcom

3 years ago

For PHP 7.3.* use FILTER_SANITIZE_ADD_SLASHES.

$str = "Is your name O'Reilly?";
$strWithSlashes = filter_var($str, FILTER_SANITIZE_ADD_SLASHES);// Outputs: Is your name O\'Reilly?
echo $strWithSlashes;?>

hybrid at n0spam dot pearlmagik dot com

21 years ago

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.

unsafed

17 years ago

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.

divinity76 at gmail dot com

5 months ago

Addslashes is *never* the right answer, it's (ab)use can lead to security exploits!

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

if you need to quote a string in xpath it's
//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
// 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.

David Spector ¶

8 năm trước

Nếu tất cả những gì bạn muốn làm là trích dẫn một chuỗi như bạn thường làm trong PHP (ví dụ: khi trả về kết quả AJAX, bên trong giá trị chuỗi JSON hoặc khi xây dựng URL với ARGS), không sử dụng AddSlashes (bạn không 'không muốn cả "và' thoát ra cùng một lúc). Thay vào đó, chỉ cần sử dụng chức năng này:

Sửa đổi điều này một cách dễ dàng để có được một chức năng trình chạy đơn.
function Quote($Str) // Double-quoting only
   
{
   
$Str=str_replace('"','\"',$Str);
    return
'"'.$Str.'"';
    }
// Quote
?>

Modify this easily to get a single-quoting function.

Stuart tại Horuskol Dot Co Dot Uk ¶

13 năm trước

Hãy cẩn thận về việc bạn sử dụng các trích dẫn kép hay đơn khi tạo chuỗi để thoát ra:

$ test = 'Đây là một dòng \ r \ nand Đây là một dòng khác \ r \ nand dòng này có \ ta tab';

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

$ test = "Đây là một dòng \ r \ nand Đây là một dòng khác \ r \ nand dòng này có \ ta tab";

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

$ test = "Đây là một dòng \ r \ nand Đây là một dòng khác \ r \ nand dòng này có \ ta tab";

Nate từ Ruggf Family.com

15 năm trước

Nếu bạn muốn thêm dấu gạch chéo vào các ký hiệu đặc biệt sẽ can thiệp vào biểu thức thông thường (tức là,. \ + *? [ ^] $ () {} =! <> | :), bạn nên sử dụng hàm preg_quote ().

Nate từ Ruggf Family.com

15 năm trước

Nếu bạn muốn thêm dấu gạch chéo vào các ký hiệu đặc biệt sẽ can thiệp vào biểu thức thông thường (tức là,. \ + *? [ ^] $ () {} =! <> | :), bạn nên sử dụng hàm preg_quote ().
    if(strpos(str_replace("\'",""," $str"),"'")!=false)
        return addslashes($str);
    else
        return $str;
}

Adrian C ¶
checkaddslashes("aa\'bb"); => aa\'bb
checkaddslashes("\'"); => \'
checkaddslashes("'");  => \'

Điều gì xảy ra khi bạn thêm AddSlashes (AddSlashes ($ str))? Đây không phải là một điều tốt và nó có thể được sửa chữa:

Chức năng checkaddslashes ($ str) {& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; if (strpos (str_replace ("\ '", "", "$ str"), "'")! = false) & nbsp; & nbsp; & nbsp; & nbsp; trả về addslashes ($ str); & nbsp; & nbsp; khác & nbsp; & nbsp; & nbsp; & nbsp; trả về $ str;}

CheckAddSlashes ("aa'bb"); & nbsp; => aa \ 'bbcheckaddslashes ("aa \' bb"); => aa \ 'bbcheckaddslashes ("\'"); => \ 'CheckAddSlashes ("'"); & nbsp; => \ '

Hy vọng điều này sẽ giúp bạn

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

Kén chọn, khó tính ¶

16 năm trước

Chức năng này không được dùng trong Php 4.0, theo bài viết này:

Ngoài ra, điều đáng nói là PostgreSQL sẽ sớm bắt đầu chặn các truy vấn liên quan đến các trích dẫn đã thoát ra bằng cách sử dụng \ làm ký tự thoát, đối với một số trường hợp, phụ thuộc vào mã hóa của chuỗi. & NBSP; Cách tiêu chuẩn để thoát khỏi trích dẫn trong SQL (không phải tất cả các cơ sở dữ liệu SQL, nhớ bạn) là bằng cách thay đổi trích dẫn đơn thành hai trích dẫn đơn (ví dụ: '' 'trở thành' '' 'cho các truy vấn).

Bạn nên xem xét các cách khác để thoát khỏi các chuỗi, chẳng hạn như "mysql_real_escape_string" (xem nhận xét bên dưới) và các chức năng thoát cụ thể của cơ sở dữ liệu khác.

PHP tại slamb dot org ¶

19 năm trước

Spamdunk tại nhà dot com, cách của bạn rất nguy hiểm trên postgresql (và có lẽ là mysql). Bạn hoàn toàn đúng khi ANSI SQL chỉ định bằng cách sử dụng 'để thoát, nhưng các cơ sở dữ liệu đó cũng hỗ trợ \ để thoát (vi phạm tiêu chuẩn, tôi nghĩ vậy). Điều đó có nghĩa là nếu chúng vượt qua trong một chuỗi bao gồm "\ '", bạn sẽ mở rộng nó thành "\' ''" (một trích dẫn thoát ra sau đó là một trích dẫn không được trục xuất. , tự làm quản trị viên, bất cứ điều gì họ muốn.)

Cách tốt nhất để an toàn và chính xác là:
    $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.)

- Không sử dụng trích dẫn ma thuật; Cách tiếp cận này là xấu. Đối với người mới bắt đầu, đó là giả định rằng bạn sẽ sử dụng đầu vào của mình trong truy vấn cơ sở dữ liệu, tùy ý. (Tại sao không thoát khỏi tất cả "

- Khi chèn vào cơ sở dữ liệu, hãy sử dụng các câu lệnh được chuẩn bị với các trình giữ chỗ. Ví dụ: khi sử dụng Pear DB:

Chuẩn bị ('Cập nhật MB_USERS Đặt mật khẩu =? WHERE Username =?'); & nbsp; & nbsp; $ dbh-> exec ($ stmt, mảng ('12345', 'bob')); ?> Lưu ý rằng không có trích dẫn xung quanh? S. Nó xử lý điều đó cho bạn tự động. Nó được đảm bảo là an toàn cho cơ sở dữ liệu của bạn. (Chỉ cần 'trên oracle, \ và' trên postgresql, nhưng bạn thậm chí không cần phải nghĩ về nó.)

CheckAddSlashes ("aa'bb"); & nbsp; => aa \ 'bbcheckaddslashes ("aa \' bb"); => aa \ 'bbcheckaddslashes ("\'"); => \ 'CheckAddSlashes ("'"); & nbsp; => \ '

Hy vọng điều này sẽ giúp bạn
Use the function above (work with arrays too).

Kén chọn, khó tính ¶
    if (is_array($str)) {
        foreach($str AS $id => $value) {
            $str[$id] = addslashes_mssql($value);
        }
    } else {
        $str = str_replace("'", "''", $str);   
    }

16 năm trước
}

Chức năng này không được dùng trong Php 4.0, theo bài viết này:
    if (is_array($str)) {
        foreach($str AS $id => $value) {
            $str[$id] = stripslashes_mssql($value);
        }
    } else {
        $str = str_replace("''", "'", $str);   
    }

& nbsp; & nbsp; trả về $ str;}
}

Lars ¶

10 năm trước

Ngay cả đối với mã hóa Backslash chuỗi JSON đơn giản, không sử dụng chức năng này. Một số xét nghiệm có thể hoạt động tốt, nhưng trong JSON, một trích dẫn duy nhất (') không được thoát ra.

Joechrz tại Gmail Dot Com ¶

16 năm trước

Dưới đây là một ví dụ về một chức năng ngăn chặn quá trình trích dẫn kép, tôi ngạc nhiên là không có thứ gì đó như thế này ... (cũng hoạt động trên mảng)

function escape_quotes($receive) {
    if (!
is_array($receive))
       
$thearray = array($receive);
    else
       
$thearray = $receive;

& nbsp; & nbsp; & nbsp; & nbsp; cho mỗi (

Array_Keys ($ thearray) là $ String) {& nbsp; & nbsp; & nbsp; & nbsp; $ thearray [$ String] = addSlashes ($ thearray [$ String]); & nbsp; & nbsp; & nbsp; & nbsp; $ thearray [$ String] = preg_replace ("/[\\/]+/", "/", $ thearray [$ String]); & nbsp; & nbsp; } is_array ($ nhận)) & nbsp; & nbsp; & nbsp; & nbsp; trả về $ thearray [0]; & nbsp; & nbsp; khác & nbsp; & nbsp; & nbsp; & nbsp; trả về $ thearray;}?>($thearray) as $string) {
       
$thearray[$string] = addslashes($thearray[$string]);
       
$thearray[$string] = preg_replace("/[\\/]+/","/",$thearray[$string]);
    }

& nbsp; & nbsp; & nbsp; & nbsp; nếu (!

is_array($receive))
        return
$thearray[0];
    else
        return
$thearray;
}
?>

DarkHunterj ¶

13 năm trước

Dựa trên: Danijel Pticar05-Aug-2009 05: 22i đề xuất phiên bản mở rộng này, để thay thế hoàn toàn AddSlashes (hoạt động cho cả hai chuỗi và mảng):
Danijel Pticar
05-Aug-2009 05:22
I recommend this extended version, to replace addslashes altogether(works for both strings and arrays):
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);
}
?>

baburaj dot ambalam tại gmail dot com ¶

2 năm trước

thoát '$' & nbsp; Sử dụng Backslash '\ $'

& nbsp; & nbsp; & nbsp; & nbsp; cho mỗi (

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