-1

Currently i'm using a lot of $_GET parameters on my site like this: http://example.com/user.php?id=1

$id=mysqli_real_escape_string($link, htmlspecialchars($_GET['id'], ENT_QUOTES));
$id=preg_replace("/[^0-9]/", "", $id);

after that i'm checking mysql for user with id 1 using mysql SELECT.

does it make any sense? or should i use something better?

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Rammy
  • 23
  • 3
  • 4
    Your script is at risk of [SQL Injection Attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) Use [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) – RiggsFolly Sep 22 '17 at 10:26
  • `$id = intval($_GET['id'];` then use prepared statements – Masivuye Cokile Sep 22 '17 at 10:27
  • I know i'm asking a lot, but maybe you could show me example of prepared parameterized statement in action? I heard that it's the safest way. i'm using only procedural type of programming in my scripts and i don't know how to work with OOP. – Rammy Sep 22 '17 at 10:39
  • @Rammy see [How Can I prevent Sql injections?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Masivuye Cokile Sep 22 '17 at 10:43

3 Answers3

1

Thats a lot of work to ensure, $_GET['id'] is actually an number... In this case you could just write

$id = (int)$_GET['id'];

Nevertheless, you should use prepared statements, to pass parameters to sql statements. If you use mysqli, you could check the php manual for some good examples.

Philipp
  • 15,377
  • 4
  • 35
  • 52
0

What you are looking for is filter_input() http://php.net/manual/en/function.filter-input.php

$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
delboy1978uk
  • 12,118
  • 2
  • 21
  • 39
0

The proper way to use user-submitted data in your queries is to use parameterized queries. I'm usually only working with PDO, but this should be a working solution using mysqli:

$mysqli->prepare("SELECT * FROM users WHERE id = ?");
$mysqli->bind_param("i", (int)$_GET['id']);

You only convert the user input to integer with (int)$_GET['id'] (read here for how arbitrary strings are converted to integers). The more important part though is the use of an parameterized query, which ensures your code is secured against SQL injection attacks.

Tobias Xy
  • 2,039
  • 18
  • 19
  • `bind_param("i", (int)$_GET['id'])` - the `(int)` isn't needed in here. Even just using `$id=(int)$_GET['id'];` is safe enough even without a prepared statement. – Funk Forty Niner Sep 23 '17 at 21:36