Do I need to use mysql_real_escape_string on all f

2019-08-19 06:35发布

I know I need to use them on user input fields such as a username entry field, but what about for radio buttons such as a gender option?

标签: php security
8条回答
干净又极端
2楼-- · 2019-08-19 07:29

A pop quiz:

Given a small HTML form snippet:

<input type="hidden" name="studentID" value="42" />
<input type="radio" name="gender" value="Robert'; DROP TABLE Students" />

and your server-side code:

$studentID = $_POST['studentID'];
$gender = $_POST['gender'];

$sql = "UPDATE Students SET gender='$gender' WHERE studentID=$studentID";
$res = mysql_query($sql);

How many ways is this code wrong?


@Basic, at mininum, here's the 'big' errors:

  1. failure to confirm that the student ID is an integer.
  2. Failing to confirm that the studentID actually is valid and exists in the DB.
  3. inserting the studentID directly into the query, potentially allowing a direct SQL injection attack.
  4. Round-tripping a critical value (studentID) through a client-side form, allowing the user to hack the form and change the gender of any student.
  5. Failure to validate the gender value, allowing arbitrary data into the database (e.g. little Bobby Tables is now of gender 'n/a')
  6. inserting the gender value directly into the query string, leading to a direct SQL injection attack (in this case, the Students table gets deleted).
  7. Failure to check the return value from mysql_query(). Queries can be syntactically perfect, yet still fail for other reasons. Never forget to check a query call's status after it completes.

Not so big a deal when only the gender of a student is at issue. Maybe a form letter goes out about "Ms. Robert" and "her" latest detention.

Very big deal if it's an online banking site and the SQL injection just transferred your chequeing account's balance to some offshore account in the Cayman Islands.

查看更多
Viruses.
3楼-- · 2019-08-19 07:30

A nice way that you could secure your inputs from $_POST is by running array_map() this is much quicker than a manual foreach().

$formData = array_map('mysql_real_escape_string', $_POST);

You can even encapsulate the process of this by making a getPost() function.

function getPost($key) {
    return array_key_exists($key, $_POST) 
        ? mysql_real_escape_string($_POST[$key]) 
        : null);
}

Hope this helps.

查看更多
登录 后发表回答