How php performs database attacks (such as SQL injection)

Source: Internet
Author: User
Tags mysql functions php mysql

PHP mysql_real_escape_string () function

PHP MySQL Functions

Definition and usage

The mysql_real_escape_string () function escapes special characters in strings used in SQL statements.

The following characters are affected:

\ X00 \ n \ r \ '"\ x1a

If yes, the function returns the escaped string. If it fails, false is returned.

Syntax
mysql_real_escape_string(string,connection)
Parameters Description
String Required. Specifies the string to be escaped.
Connection Optional. MySQL connection is required. If not specified, use the previous connection.
Description

This function willStringThe special character escape in, and considering the connected Current Character Set, can be safely used for mysql_query ().

Tips and comments

Tip: You can use this function to prevent database attacks.

Example 1
 Mysql_real_escape_string ($ user); $ Pwd =mysql_real_escape_string($pwd); $ SQL = "SELECT * FROM users WHEREuser = '". $ user. "'AND password = '". $ pwd. "'" // more code mysql_close ($ con);?>
Example 2

Database attacks. This example shows what will happen if we do not apply the mysql_real_escape_string () function to the user name and password:

 

The SQL query will be like this:

SELECT * FROM usersWHERE user='john' AND password='' OR ''=''

This means that any user can log on without entering a valid password.

Example 3

The correct method to prevent database attacks:

 Stripslashes ($ value);} // If it is not a number, enclose the quotation mark if (! Is_numeric ($ value) {$ value = "'".mysql_real_escape_string($value). "'";} Return $ value;} $ con = mysql_connect ("localhost", "hello", "321"); if (! $ Con) {die ('could not connect :'. mysql_error ();} // perform security SQL $ user = check_input ($ _ POST ['user']); $ pwd = check_input ($ _ POST ['pwd']); $ SQL = "SELECT * FROM users WHEREuser = $ user AND password = $ pwd"; mysql_query ($ SQL ); mysql_close ($ con);?>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.