Reedyn / Just-Another-Webshop

Webshop built for a university PHP project
2 stars 1 forks source link

Add protection against SQL-Injection and hacking of the Database #32

Closed Reedyn closed 10 years ago

Reedyn commented 10 years ago

The following two methods was suggested during our lecture.

mysqli_real_escape_string()

Example of protection using mysqli_real_escape_string()

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!$mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
    printf("Error: %s\n", $mysqli->sqlstate);
}

$city = $mysqli->real_escape_string($city);

/* this query with escaped $city will work */
if ($mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
    printf("%d Row inserted.\n", $mysqli->affected_rows);
}

$mysqli->close();
?>

Encryption using MD5

Pseudocode example of implementation

$saltedPassword = $password + $salt;
$md5hash =  RUN $saltedPassword THROUGH md5hash
SAVE $md5hash in DATABASE