1

I'm making an e-commerce site in PHP 7 and HTML 5. When I enter login details, admin.php just refreshes and does not redirect to index.php, as it should.

I've already tried using actual cookies, although I would prefer to just use session cookies for security reasons.

ADMIN LOGIN.php CODE
<?php
session_start();
if(isset($_SESSION["manager"])){
  header("location: index.php");
  exit();
}
?>
<?php
if (isset($_POST["username"])&&isset($_POST["password"])){
  $manager = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["username"]);
  $password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password"]);

  include "../storescripts/connect_to_mysql.php";
  //$sqlquery =
  $sql = mysqli_query($con, "SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1");
  $existCount=mysqli_num_rows($sql);
  if($existCount == 1){
    while($row = mysqli_fetch_array($sql)){
      $id = $row["id"];
    }
    $_SESSION["id"] = $id;
    $_SESION["manager"] = $manager;
    $_SESSION["password"] = $password;
    header("location: index.php");
    exit();
  } else {
    // code...
    echo 'Invalid Log In Credentials<br><br>';
    echo'<a href="index.php">Click Here To Re-Enter Credentials</a>';
    exit();
  }
}
?>

INDEX.php CODE
<?php
session_start();
if (!isset($_SESSION["manager"])){
  header("location: admin_login.php");
  exit();
}

$managerID = preg_replace('#[^0-9]#i', '', $_SESSION["id"]);
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["manager"]);
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["password"]);

include "../storescripts/connect_to_mysql.php";
$sql = mysqli_query($con, "SELECT * FROM admin WHERE id='$managerID' AND     username='$manager' AND password='$password' LIMIT 1");
$existCount = mysqli_num_rows($sql);
if ($existCount == 0){
  header("location: ../index.php");
  exit();
}
?>

I expected the page to redirect to index.php once the session cookie was set, but it does not do this.

  • Possible duplicate of [How do I make a redirect in PHP?](https://stackoverflow.com/questions/768431/how-do-i-make-a-redirect-in-php) – Masivuye Cokile May 27 '19 at 15:48

1 Answers1

0

You must change your redirect calls. I'll recommend you to ecapsulate that logic in a function.

function redirectTo($uri)
{
    header('Location: '.$uri); // Where to redirect. 
    http_response_code(301); // The response code to redirection.
    exit(); // End of script
}

Then in your client code, to redirect to index.php

redirectTo('/index.php'); // Note the removal of the dots. Your file must be relative to your document_root, not your filesystem.

Done.

PS: As a side comment, and don't take this as a personal attack; this is not the right way to code in PHP. Please take a look at: https://phptherightway.com/. You must use proper HTTP abstractions nowadays. Check Zend Diactoros. :)