user1161867
user1161867

Reputation: 141

php query string validation

In my php code i can get data with php $_GET method. Here is code look like this..

<?php 
<a href='userprofile.php?uname=$uname'>$uname</a>
?>

If i click the the link it's show user profile page and so that userprofile.php page's url look like this.

http://localhost/evantechbd1/userprofile.php?uname=shibbir

My question is how do i prevent this url from sql injection or any other attack.

If I write:

http://.......uname=shibbir'OR'='-1-'

then it's show:

SHIBBIR%27OR%27%3D%27-1-%27'S PROFILE.

BUT I want whatever text is provided to that link it's must be show only valid username profile page.

Any idea.

Upvotes: 0

Views: 1391

Answers (4)

Taipo
Taipo

Reputation: 76

The other issue then is cross site scripting exploits. There are several ways of dealing with this but the usual way is to check that $_GET[ 'uname' ] exists as a username in your database first before using it in the html block.

Upvotes: 0

jeroen
jeroen

Reputation: 91762

The best way is to use a prepared statement, see the examples here, although I normally do some data validation even on data that is going to be used in a prepared statement.

For example, if someone registers, there are only certain characters allowed in a username and I use that same check when someone enters a username to be fetched.

Upvotes: 1

lorenzo-s
lorenzo-s

Reputation: 17010

Before using $uname in your SQL, escape it.
For example, if you use the old but gold PHP MySQL extension:

$uname = mysql_real_escape_string($uname);
$res = mysql_query("SELECT * FROM users WHERE name = '$uname'");

If $uname is shibbir'OR'='-1-', after using the function I wrote, it will be shibbir\'OR\'=\'-1-\', that is unable to break your query.

Read more here:

http://php.net/manual/en/function.mysql-real-escape-string.php
http://www.php.net/manual/en/security.database.sql-injection.php

Upvotes: 0

Marc B
Marc B

Reputation: 360772

You can't prevent someone from ATTEMPTING the attack, you can only prevent the attack from succeeding. However, what that prevention actually IS depends entirely on what you're going to use the database. There is no 'magic bullet' function that will make every bit of data safe in every case, as many 'sanitization' functions destroy data that is necessary in other usage cases.

e.g. there is no point in doing an SQL injection attack prevention with (say) mysql_real_escape_string() if the bad data is never going to be used in an SQL query. Doing htmlspecialchars() when the string is not going to be used in HTML context is similarly useless.

Upvotes: 0

Related Questions