Login Form (PHP/MYSQLI)

This is my code for my login form at the moment, but it just doesn’t seem to be working. I’ve meddled with things so much that I’m not even sure what’s wrong any more.

[php]<?php
if(isset($_POST[‘login’]))
{
$username = $_POST[‘username’];
$password = md5($_POST[‘password’]);
$res = $mysqli->prepare(“SELECT * FROM users WHERE username = ? && password = ?”);
$res->bind_param(“ss”, $username, $password);
$res->execute();
$res->store_result();
$rows = $res->num_rows;
if($rows == 0)
{
header (‘Location: …/index.php’);
}else{
$query = “SELECT id FROM users WHERE username = $username”;
if ($stmt = $mysqli->prepare($query))
{
$stmt->execute();
$stmt->bind_result($id);
while ($stmt->fetch_assoc())
{
$_SESSION[‘uid’] = $id;
header (‘Location: …/yourstory.php?id=’.$_SESSION[‘uid’]);
}
}
}
}
?>[/php]

Any help is greatly appreciated.

You should use a proper editor / IDE. It will show errors and help you coding :slight_smile:

There are a few things wrong here.

1: Do not use MD5 for password hashing, use Bcrypt or PBKDF2
[php]$password = md5($_POST[‘password’]);[/php]

2: Prepared statements won’t help you from SQL injection hacks if you insert variables directly into the query. Change this query to the same format as the last one.
[php]$query = “SELECT id FROM users WHERE username = $username”;[/php]

3: Accidental assignment in a condition (using only one = will set $stmt equal to $mysqli->prepare($query), not check if it’s return value is true.
[php]if ($stmt = $mysqli->prepare($query))[/php]

4: you shouldn’t end php files with ?> if you don’t follow it with html. PHP doesn’t care if you don’t end execution before the end of the file. But if you have anything after the ?> you may get huge trouble elsewhere in the code to modify headers / use cookies.

Sponsor our Newsletter | Privacy Policy | Terms of Service