非法字元過濾_PHP教程

來源:互聯網
上載者:User
非法字元過濾本文章主要是講 php 過濾非法字元沒講asp過濾非法字元 的函數但是思想都一樣的.

) 過濾影響MySQL正常啟動並執行字元。

當需要把使用者輸入的內容(有可能包含單引號、雙引號 、反斜線、空字元 NUL )代入到mysql的語句 中執行時,應該把APACHE中的magic_quotes_gpc項設成On。

如果APACHE中的此項設成Off時,也可用php的函數addslashes()達到相同的目的,但這兩種手段不能同時使用,否則會出現重複替換,出現錯誤。

範例:

PHP代碼

if (get_magic_quotes_gpc()) {

$content=$_POST["content"];

} else {

$content=addslashes($_POST["content"]);

}

?>

當然,如果APACHE中的magic_quotes_gpc項為On,但有時又不想轉義某項的特殊字元,可以使用stripslashes()去掉其中的 \

2) 過濾影響MSSQL正常啟動並執行字元。

當需要把使用者輸入的內容(有可能包含單引號)代入到mssql的語句中執行時,應該把APACHE中的magic_quotes_sybase項設成On,此時magic_quotes_gpc項不再生效。

如果APACHE中的此項設成Off時,php中並沒有合適的函數達到相同的目的,只能使用字串替換函數來達到此目的。

範例:

PHP代碼

$content=str_replace("'","''"$_POST["content"]);

?>

現在10.218.17.53上的PHP既要訪問mysql又要訪問mssql,APACHE中的設定不能兼顧兩種資料庫,所以只對mysql做了相應設定。

2. 應對使用者輸入包含SQL語句的一個措施。

以下兩種SQL寫法都比較普遍,但安全程度是不同的,當使用者提交的$id='1 and 1=2 union select ...'時第一種就會顯示出不該顯示的資料,而第二種就相對安全些。

SQL代碼
Select * FROM article Where articleid=$id
Select * FROM article Where articleid='$id'

3. 防止使用者輸入的內容因包含html標籤或javascript而影響頁面的正常顯示。

可以用htmlspecialchars()過濾其中的 & " < >

PHP代碼
$content = htmlspecialchars($content);

4. 當頁面要顯示的內容包含斷行符號換行時,可以使用nl2br()來達到頁面上換行的效果。
方法一.
function chkstr($paravalue,$paratype) //過濾非法字元
{
if($paratype==1)
{
$inputstr=str_replace("'","''",$paravalue);
}
elseif($paratype==2)
{
$inputstr=str_replace("'","",$paravalue);
}
return $inputstr;
}
$user1=chkstr($_GET["user"],1);
$user2=chkstr($_GET["user"],2);
//$user=$_GET["user"];
print "方式1-----------------
";
print "$user1
";
print "方式2-----------------
";
print "$user2
";
?>
方法二.


//用法:qstr($str, get_magic_quotes_gpc())
function qstr($string, $magic_quotes=false, $tag=false)
{
$tag_str = '';
if ($tag) $tag_str = "'";
if (!$magic_quotes) {
if (strnatcmp(PHP_VERSION, '4.3.0') >= 0) {
return $tag_str.mysql_real_escape_string($string).$tag_str;
}
$string = str_replace("'", "[url=file://\\]\\'[/url]" , str_replace('\\', '\\\\', str_replace("\0", "[url=]\\\0[/url]", $string)));
return $tag_str.$string.$tag_str;
}
return $tag_str.str_replace('\\"', '"', $string).$tag_str;
}
?>

http://www.bkjia.com/PHPjc/629753.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/629753.htmlTechArticle非法字元過濾 本文章主要是講 php 過濾非法字元 沒講asp過濾非法字元 的函數但是思想都一樣的. ) 過濾影響MySQL正常啟動並執行字元。 當需要把...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.