The script below is a script I¨ve found online, which should be Sql Injection safe. Id like someone to confirm this. My main question in this post is, how can I get this script XSS safe in the same script?
In the end of my post I've added a PHP script that should prevent XSS. But I dont know how I should write that XSS function within this anti-sql-injection script.
if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $password);
$stmt->fetch();
// Account exists, verify the password.
if ($_POST['password'] === $password) { // Ikke Kryptert
session_regenerate_id();
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['username'];
$_SESSION['id'] = $id;
echo 'Welcome ' . $_SESSION['name'] . '!';
} else {
// Incorrect password
echo 'Incorrect username and/or password!';
}
} else {
// Incorrect username
echo 'Incorrect username and/or password!';
}
Before I learned I need to prevent SQL injection with a code as the one above, I've only used my login script like this.
function valid($info) {
$info = htmlspecialchars($info);
$info = trim($info);
$info = stripslashes($info);
return $info;
}
$username = valid($_POST['username']);
or
$_SESSION['name'] = valid($_POST['username']);
How can I write my script so that it is both Sql-injection safe, and XSS safe in the same login script?