Home Backend Development PHP Tutorial How to prevent sql injection in php website?

How to prevent sql injection in php website?

Jul 25, 2016 am 09:13 AM

The operational security of the website is definitely an issue that every webmaster must consider. As we all know, most hackers attack websites by using SQL injection. This is what we often say why?

The most original static website is the safest. Today we will talk about the security specifications of PHP injection to prevent your website from being injected by SQL.

Nowadays, the mainstream website development language is still PHP, so let’s start with how to prevent SQL injection on PHP websites:

Security Prevention of Php Injection Through the above process, we can understand the principles and techniques of php injection. Of course, we can also develop corresponding prevention methods:
The first is the security settings of the server. Here are mainly the security settings of php+mysql and the security settings of the Linux host. To prevent php+mysql injection, first set magic_quotes_gpc to On and display_errs to Off. If it is an id type, we use intval() to convert it into an integer type, as shown in the code:



$idintval($id);
mysql_query”*fromexamplewherearticieid’$id’”; Or write like this: mysql_query(”SELECT*FROMarticleWHEREarticleid”.intval($id).””)
If it is a character type, use addslashes() to filter it, and then filter "%" and "_", such as:
$searchaddslashes($search);
$searchstr_replace(“_”,”_”,$search);
$searchstr_replace(“%”,”%”,$search);
Of course, you can also add PHP universal anti-injection code:
/*****************************
PHP universal anti-injection security code
Description:
Determine whether the passed variable contains illegal characters
Such as $_POST, $_GET
Function:
Anti-injection
  1. *******************************/
  2. //Illegal characters to be filtered
  3. $ArrFiltratearray("'",";","union");
  4. //The url to be redirected after an error occurs, if not filled in Default previous page
  5. $StrGoUrl"";
  6. //Whether there is a value in the array
  7. functionFunStringExist($StrFiltrate,$ArrFiltrate){
  8. feach($ArrFiltrateas$key>$value){
  9. if(eregi ($value,$StrFiltrate)){
  10. returntrue;
  11. }
  12. }
  13. returnfalse;
  14. }
  15. //Merge $_POST and $_GET
  16. if(function_exists(array_merge)){
  17. $ArrPostAndGetarray_ merge ($HTTP_POST_VARS,$HTTP_GET_VARS);
  18. }else{
  19. feach($HTTP_POST_VARSas$key>$value){
  20. $ArrPostAndGet[]$value;
  21. }
  22. feach($HTTP_GET_VARSas$key>$value) {
  23. $ArrPostAndGet[]$value;
  24. }
  25. }
  26. //Verification starts
  27. feach($ArrPostAndGetas$key>$value){
  28. if(FunStringExist($value,$ArrFiltrate)){
  29. echo "alert(/"Neeao prompt, illegal character/");";
  30. if(empty($StrGoUrl)){
  31. echo "histy.go(-1);";
  32. }else{
  33. echo "window.location/"".$StrGoUrl."/";";
  34. }
  35. exit;
  36. }
  37. }
  38. ?>
  39. /*********** ******************
Copy code
Save as checkpostget.php
Then add include("checkpostget.php"); before each php file
****************************/
In addition, the administrator username and password are md5 encrypted, which can effectively prevent PHP injection.
There are also some security precautions that need to be strengthened on the server and mysql.
For security settings of linux server:
To encrypt the password, use the "/usr/sbin/authconfig" tool to turn on the password shadow function and encrypt passwd.
To prohibit access to important files, enter the Linux command interface and enter at the prompt:
#chmod600/etc/inetd.conf//Change the file attributes to 600
#chattr+I /etc/inetd.conf // Ensure that the file owner is root
#chattr–I /etc/inetd.conf //Restrict changes to this file
It is forbidden for any user to change to the root user through the su command
Add the following two lines at the beginning of the su configuration file, that is, the /etc/pam.d/ directory:
Auth sufficient /lib/security/pam_rootok.sodebug
Auth required /lib/security/pam_whell.sogroupwheel
Delete all special accounts
#userdel lp etc. Delete user
#groupdellpetc delete group
Ban unused suid/sgid programs
#find/-typef(-perm-04000 -o–perm-02000)-execls–lg{};



http://hi.baidu.com/bigideaer/bl... 7e76e11a4cffd0.html

To determine whether the passed variables contain illegal characters, we put the following code into a public file, such as security.inc.php. Include this file in each file, then all the files submitted to any program can be After the variables are filtered, we achieve the effect once and for all.



Brief description: /***************************
Description:
Determine whether the passed variable contains illegal characters
Such as $_POST, $_GET
Function: Anti-injection
**************************/

The code is as follows:

  1. //Illegal characters to be filtered
  2. $ArrFiltratearray("",";","union");
  3. //URL to be redirected after an error , if not filled in, it will default to the previous page
  4. $StrGoUrl"";
  5. //Whether there is a value in the array
  6. functionFunStringExist($StrFiltrate,$ArrFiltrate){
  7. feach($ArrFiltrateas$key>$value){
  8. if(eregi($value,$StrFiltrate)){
  9. returntrue;
  10. }
  11. }
  12. returnfalse;
  13. }

  14. //Merge $_POST and $_GET
  15. if(function_exists( array_merge) ){
  16. $ArrPostAndGetarray_merge($HTTP_POST_VARS,$HTTP_GET_VARS);
  17. } else{
  18. feach($HTTP_POST_VARSas$key>$value){
  19. $ArrPostAndGet[]$value;
  20. }
    feach($HTTP_GET_VARSas $key>$value){

  21. $ArrPostAndGet[]$value;

  22. }

  23. }


  24. //Verification starts

  25. feach($ArrPostAndGetas$key>$value){

  26. if(FunStringExist($ value,$ArrFiltrate)){

  27. echo"alert("Illegal character");";

  28. if(emptyempty($StrGoUrl)){

  29. echo"< ;scriptlanguage"javascript">histy.go(-1);";

  30. }else{

  31. echo"window.location"".$StrGoUrl."" ;";

  32. }

  33. exit;

  34. }

  35. }

  36. ?>


Copy the codeSave as checkpostget.php
Then add include("checkpostget.php"); in front of each php file


Method 2

The code is as follows:
    /*Filter all GET variables*/

  1. feach($_GETas$get_key>$get_var)

  2. {

  3. if(is_numeric($get_var)){

  4. $get[strtolower($ get_key)]get_int($get_var);

  5. }else{

  6. $get[strtolower($get_key)]get_str($get_var);

  7. }

  8. }


  9. /*Filter all POST variables* /

  10. feach($_POSTas$post_key>$post_var)

  11. {

  12. if(is_numeric($post_var)){

  13. $post[strtolower($post_key)]get_int($post_var);

  14. }else{

  15. $post[strtolower($post_key)]get_str($post_var);

  16. }

  17. }


  18. /*Filter function*/

  19. //Integer filter function

  20. functionget_int($number)

  21. {

  22. returnintval($number);

  23. }

  24. //String filter function

  25. functionget_str($string)

  26. {

  27. if(!get_magic_quotes_gpc()){

  28. returnaddslashes($string);

  29. }

  30. return$string;

  31. }
Copy codeThe first one is the method of escaping data

The second method is written in a separate file and imported into every PHP file

Then you can escape every data

functionsaddslashes($string){

if(is_array($string)){

feach($stringas$key>$val){

$string[$key]saddslashes($val);

}

}else{

$stringaddslashes($string);

}

return$string;

}





################################################ ###############

$magic_quoteget_magic_quotes_gpc();

if(empty($magic_quote)){

$_GETsaddslashes($_GET);

$_POSTsaddslashes($_POST);

}

This topic was unpinned by Xiaobei on 2015-9-20 13:05


Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles