开发者

How to use $_GET securely?

开发者 https://www.devze.com 2023-03-25 03:21 出处:网络
I need to use a get function to retrieve $title variable from a url. $title=$_GET[\"title\"]; The $title is later used in a MySQL query.

I need to use a get function to retrieve $title variable from a url.

$title=$_GET["title"];

The $title is later used in a MySQL query.

The question is how to make this secure? In other words, how to neutralize any malicious codes sent through t开发者_开发问答he URL.


(For a value of "secure" equal to "to prevent it breaking the database"): use any database API that uses bound parameters.

Bound parmeters tend to let the database handle the escaping (so uses escaping routines written by the database authors rather then the language authors) and uses a syntax that is less prone to being forgotten about for that one vital escape then manually escaping each piece of input data with (for example) mysql_real_escape_string.

You might need to take other steps later before you do something with the data in a different context (e.g. to make it safe to insert into an HTML document)


You must use mysql_real_escape_string() to escape all characters that could interfere with you database. If you're displaying this title, you should also make use of htmlentities() or striptags()


As of PHP 5.2, you can use filter_input() and filter_input_array() to sanitize and validate the the $_GET or $_POST data.

For example:

$my_string = filter_input(INPUT_GET, 'my_string', FILTER_SANITIZE_STRING);

Read more about that in this article here.

For SQL queries, it's very recommended that you use PDO with prepared statements to protect from SQL injections. You can read about PDO in the PHP Manual here.


You can use mysql_real_escape_string function (Escapes special characters in a string for use in an SQL statement)

Php Manuel


Use query parameters. There is a number of different ways to connect to mysql from PHP, and they way to use parameters varies a little from framework to framework. Here is an example using PDO:

$dbh = new PDO('mysql:dbname=test;host=127.0.0.1', 'username', 'password');
$sth = $dbh->prepare("select * from table where title = :title")
$sth->execute(array(':title' => $_GET["title"]));
$rows = $sth->fetchAll();

var_dump($rows);
0

精彩评论

暂无评论...
验证码 换一张
取 消