DanStarck
DanStarck

Reputation: 27

prevent sql injection by converting string to arrays

In my Login forms I hash username and password before I execute the queries

... class ...

private $username;
private $password;
protected function Login(){
    $user = hash('sha256', $this->username);
    $pass = hash('sha256', $this->password);
    $this query = "..."
    ...
}

and in other kind of forms (like Search forms) I convert the strings to arrays and then I execute the queries, that way the query would look like this:

$searchstring = explode(' ', $search);
//.... Some lines of PHP code... and the resulting query is: ...
$this->query = "SELECT... WHERE name LIKE 'DELETE%' OR name LIKE 'FROM%' ";
$this->query.= " OR name LIKE 'USERS%' OR name LIKE 'WHERE%' OR name LIKE '1%'";

Is this enough to prevent sql injection? thanks

Upvotes: 1

Views: 531

Answers (3)

Anonymous
Anonymous

Reputation: 4632

Alternatively you can convert it to binary:

function mssql_escape($data) {
    if(is_numeric($data))
        return $data;
    $unpacked = unpack('H*hex', $data);
    return '0x' . $unpacked['hex'];
}

... If in case you are not on mysql db.

Upvotes: 0

pzirkind
pzirkind

Reputation: 2338

There are some very easy steps you can take to make the code more secure:

$query= mysqli_real_escape_string($database_connection, $user)

this escapes any dangerous characters that can adversely affect SQL string

$query = mysqli_real_escape_string($database_connection, trim($user))

in this step we added the trim function which takes out any whites spaces - which are used to launch SQL Injection attacks

You can see more about this here

Upvotes: 0

Anthony Mills
Anthony Mills

Reputation: 8784

Don't trust in your own abilities to prevent SQL injection! Many better heads than yours have fallen to it.

Use mysqli or PDO and parameterized queries. This has the side benefit of allowing your database to cache query plans too.

Upvotes: 5

Related Questions