php防止sql注入的代碼

來源:互聯網
上載者:User
  1. /*************************

  2. 說明:
  3. 判斷傳遞的變數中是否含有非法字元
  4. 如$_POST、$_GET
  5. 功能:防注入
  6. **************************/

  7. //要過濾的非法字元

  8. $ArrFiltrate=array("'",";","union");
  9. //出錯後要跳轉的url,不填則預設前一頁
  10. $StrGoUrl="";
  11. //是否存在數組中的值
  12. function FunStringExist($StrFiltrate,$ArrFiltrate){
  13. foreach ($ArrFiltrate as $key=>$value){
  14. if (eregi($value,$StrFiltrate)){
  15. return true;
  16. }
  17. }
  18. return false;
  19. }

  20. //合并$_POST 和 $_GET

  21. if(function_exists(array_merge)){
  22. $ArrPostAndGet=array_merge($HTTP_POST_VARS,$HTTP_GET_VARS);
  23. }else{
  24. foreach($HTTP_POST_VARS as $key=>$value){
  25. $ArrPostAndGet[]=$value;
  26. }
  27. foreach($HTTP_GET_VARS as $key=>$value){
  28. $ArrPostAndGet[]=$value;
  29. }
  30. }

  31. //驗證開始

  32. foreach($ArrPostAndGet as $key=>$value){
  33. if (FunStringExist($value,$ArrFiltrate)){
  34. echo "";
  35. if (emptyempty($StrGoUrl)){
  36. echo "";
  37. }else{
  38. echo "";
  39. }
  40. exit;
  41. }
  42. }
  43. ?>
複製代碼

儲存為 checkpostandget.php,然後在每個php檔案前加include(“checkpostandget.php“);即可。

方法二

  1. /* 過濾所有GET過來變數 */

  2. foreach ($_GET as $get_key=>$get_var)
  3. {
  4. if (is_numeric($get_var)) {
  5. $get[strtolower($get_key)] = get_int($get_var);
  6. } else {
  7. $get[strtolower($get_key)] = get_str($get_var);
  8. }
  9. }

  10. /* 過濾所有POST過來的變數 */

  11. foreach ($_POST as $post_key=>$post_var)
  12. {
  13. if (is_numeric($post_var)) {
  14. $post[strtolower($post_key)] = get_int($post_var);
  15. } else {
  16. $post[strtolower($post_key)] = get_str($post_var);
  17. }
  18. }

  19. /* 過濾函數 */

  20. //整型過濾函數
  21. function get_int($number)
  22. {
  23. return intval($number);
  24. }
  25. //字串型過濾函數
  26. function get_str($string)
  27. {
  28. if (!get_magic_quotes_gpc()) {
  29. return addslashes($string);
  30. }
  31. return $string;
  32. }
  33. ?>

複製代碼
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.