1. 程式人生 > >PHP之string之addslashes()函數使用

PHP之string之addslashes()函數使用

it! quotes add specific http post dir cookie span

addslashes

  • (PHP 4, PHP 5, PHP 7)
  • addslashes — Quote string with slashes
  • addslashes — 使用反斜線引用字符串

Description

string addslashes ( string $str )
// Returns a string with backslashes added before characters that need to be escaped. These characters are:
// 返回字符串,該字符串為了數據庫查詢語句等的需要在某些字符前加上了反斜線。這些字符: 
- single quote (
') 單引號(') - double quote (") 雙引號(") - backslash (\) 反斜線(\) - NUL (the NUL byte) NULNULL 字符)
  • A use case of addslashes() is escaping the aforementioned characters in a string that is to be evaluated by PHP:
  • 一個使用 addslashes() 的例子是當你要往數據庫中輸入數據時。
<?php
$str = "O'Reilly?"
; eval("echo '" . addslashes($str) . "';");
  • Prior to PHP 5.4.0, the PHP directive magic_quotes_gpc was on by default and it essentially ran addslashes() on all GET, POST and COOKIE data. addslashes() must not be used on strings that have already been escaped with magic_quotes_gpc, as the strings will be double escaped. get_magic_quotes_gpc() can be used to check if magic_quotes_gpc is on.
  • 例如,將名字 O‘reilly 插入到數據庫中,這就需要對其進行轉義。 強烈建議使用 DBMS 指定的轉義函數 (比如 MySQL 是 mysqli_real_escape_string(),PostgreSQL 是 pg_escape_string()),但是如果你使用的 DBMS 沒有一個轉義函數,並且使用 ?來轉義特殊字符,你可以使用這個函數。 僅僅是為了獲取插入數據庫的數據,額外的 ?並不會插入。 當 PHP 指令 magic_quotes_sybase 被設置成 on 時,意味著插入 ‘ 時將使用 ‘ 進行轉義。

  • The addslashes() is sometimes incorrectly used to try to prevent SQL Injection. Instead, database-specific escaping functions and/or prepared statements should be used.
  • PHP 5.4 之前 PHP 指令 magic_quotes_gpc 默認是 on, 實際上所有的 GET、POST 和 COOKIE 數據都用被 addslashes() 了。 不要對已經被 magic_quotes_gpc 轉義過的字符串使用 addslashes(),因為這樣會導致雙層轉義。 遇到這種情況時可以使用函數 get_magic_quotes_gpc() 進行檢測。

Parameters

str

  • The string to be escaped.
  • 要轉義的字符。

Return Values

  • Returns the escaped string.
  • 返回轉義後的字符。

Examples

<?php
/**
 * Created by PhpStorm.
 * User: zhangrongxiang
 * Date: 2018/2/13
 * Time: 下午7:41
 */
$str = 'just do it!';
//  just do it!
echo addslashes( $str ) . PHP_EOL;
$str = "just do it!";
//  just do it!
echo addslashes( $str ) . PHP_EOL;
$str = '\a\b\'';
//  \\a\\b\'
echo addslashes( $str ) . PHP_EOL;
$str = '\\';
//  \\
echo addslashes( $str ) . PHP_EOL;

See

  • http://php.net/manual/en/function.addslashes.php

All rights reserved

PHP之string之addslashes()函數使用