1

This is my code and I'm having a problem on it it says that it has a redirect loop

<?php
session_start();
require_once("db_connection.php");

if (!$connect) {
    die("Connection failed: " . mysqli_connect_error());
}

$username = $_POST['username'];
$password = $_POST['password'];

$query = "SELECT * FROM admins WHERE username='{$username}' AND password='{$password}'";
$result = mysqli_query($connect , $query);

if (isset($result)) {
    echo "success";
}

$rows = mysqli_fetch_assoc($result);

if(mysqli_num_rows($result)==1){
    $_SESSION['id'] = $rows['id'];
}

if(mysqli_num_rows($result)!=1 || !isset($rows['id'])){
    header("location: login.php");
}

?>

and when I try to launch it gives me on the browser

This webpage has a redirect loop

ERR_TOO_MANY_REDIRECTS`

John Conde
  • 217,595
  • 99
  • 455
  • 496
Bouzaid
  • 66
  • 8
  • 1
    In addition to sql injection you should also take care of not storing passwords in clear text. Hashing them using SHA256 and salting them would help. But why reinvent the wheel? Use some ready made authentication mechanism. – Tarik Aug 08 '15 at 01:53
  • yes I know ! this is only for educational purposes ! I'm still learning, and this is the application of what I've learned – Bouzaid Aug 09 '15 at 01:21

1 Answers1

7

You have a basic logic error. You are trying to run this code when the pages loads but don't have any $_POST values yet because no form has been submitted. So your query fails. Since your code says to go back to this page if the query finds no rows the cycle starts all over again.

To fix this wrap all of this code in an if statement that checks to see if the form has been submitted. You can check the $_SERVER superglobal which contains and key called REQUEST_METHOD which will tell you if the page was requested via POST (as is common when a form is submitted) or GET (as is common on a "typical" page load). If it's value is "POST" then the form was submitted and you can process the data, if not, ignore that code.

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // your code goes here
}

FYI, you are wide open to SQL injections

Community
  • 1
  • 1
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • Indeed, SQL injection is the first thought that came to my mind seeing this code. – Tarik Aug 08 '15 at 01:50
  • yes I know ! this is only for educational purposes ! I'm still learning, and this is the application of what I've learned – Bouzaid Aug 09 '15 at 01:22