清除惡意代碼的PHP腳本

jopen 11年前發布 | 22K 次閱讀 PHP腳本 PHP開發

在插入數據庫中的數據時,你必須要很小心SQL注入和其他試圖插入惡意數據到DB中。下面的函數可能是最完整和最有效的方式在將數據保存至數據庫之前,對其進行”消毒“。

function cleanInput($input) {

$search = array( '@<script[^>]?>.?</script>@si', // Strip out javascript '@<[\/!]?[^<>]?>@si', // Strip out HTML tags '@<style[^>]?>.?</style>@siU', // Strip style tags properly '@<![\s\S]?--[ \t\n\r]>@' // Strip multi-line comments );

$output = preg_replace($search, '', $input);
return $output;

} ?> <?php function sanitize($input) { if (is_array($input)) { foreach($input as $var=>$val) { $output[$var] = sanitize($val); } } else { if (get_magic_quotes_gpc()) { $input = stripslashes($input); } $input = cleanInput($input); $output = mysql_real_escape_string($input); } return $output; }</pre>下面是一些使用的例子:

<?php
  $bad_string = "Hi! <script src='; It's a good day!";
  $good_string = sanitize($bad_string);
  // $good_string returns "Hi! It\'s a good day!"

// Also use for getting POST/GET variables $_POST = sanitize($_POST); $_GET = sanitize($_GET); ?></pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!