I was wondering if it is at all possible for a hacker to perform an SQL injection attack using just letters and numbers. For example, let's take a look at this PHP code which uses regular expressions instead of the builtin PHP functions:
<?php
$id = preg_replace('/[^a-zA-Z0-9]/', '', $_GET['id']);
$result = $mysqli->query("SELECT * users WHERE id = '".$id."'");
In case your wondering what the code does, it removes all characters that are not letters or numbers and executes that query it in MySQL. I was wondering if a hacker could be able to exploit that code in some way and if not, what might the difference be between that and mysqli::prepare
or mysqli::escape_string
?
[\W_]
instead of that long regex (note the uppercase W), also don't forget to always check if get/post variables are set. You may use something like the following$id = preg_replace('/[\W_]/', '', (isset($_GET['id']) ? $_GET['id']:0));
.0
is the default value if it does not exist.