Home >Backend Development >PHP Tutorial >PHP code to prevent sql injection

PHP code to prevent sql injection

WBOY
WBOYOriginal
2016-07-25 09:03:441087browse
  1. /***************************

  2. Description:
  3. Determine whether the passed variable contains illegal characters
  4. such as $_POST, $_GET
  5. Function: Anti-injection
  6. * *************************/

  7. //Illegal characters to be filtered

  8. $ArrFiltrate=array("'", ";","union");
  9. //The url to jump to after an error occurs. If not filled in, the previous page will be defaulted
  10. $StrGoUrl="";
  11. //Whether there is a value in the array
  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. //Merge $_POST and $_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. //Verification starts

  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. ? >
Copy the code

and save it as checkpostandget.php, and then add include("checkpostandget.php"); in front of each php file.

Method 2

  1. /* Filter all GET variables*/

  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. < ;p>/* Filter all POST variables*/
  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. /* Filter function*/

  20. // Integer filter function
  21. function get_int($number)
  22. {
  23. return intval($number);
  24. }
  25. //String filter function
  26. function get_str($string)
  27. {
  28. if (!get_magic_quotes_gpc()) {
  29. return addslashes($string);
  30. }
  31. return $string;
  32. }
  33. ?>

Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn