Это код, на котором я включил сеансы, и он не работает. Я не уверен, что я сделал неправильно. Я включил сессии в неправильном месте на моей странице входа? Я новичок в PHP, поэтому любая помощь будет отличной. Я включил свой логин. php и мою домашнюю страницу. php, которые я хочу защитить.
Логин. php
<?php
// Always start this first
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
//connect to server and database
$conn = mysqli_connect ("localhost", "root", "", "horses");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo "Success: a propper connection was made! <br>";
echo "Host information: " . mysqli_get_host_info($conn);
// Query the users table if there is matching rows equal to the $username
$myQuery = "SELECT * FROM users WHERE username='$username'";
$result = mysqli_query ($conn, $myQuery);
$exists = $result->num_rows; //checks if username exists
$table_users = "";
$table_password= "";
if ($exists > 0)
{ //if there is no returning rows or no existing username
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{ //DISPLAY ALL ROWS FROM QUERY
// THE FIRST USERNAME ROW IS PASSED ONTO THE $TABLE_USERS, AND SO ON UNTILL THE QUERY IS FINISHED
$table_users = $row ['username'];
// the first password row is PAassed on to the $table_users and so on until the query is finished
$table_password = $row['password'];
$table_role = $row['RoleID'];
}//while
// check if there are any mactching fields
if ($username == $table_users && ($password == $table_password))
{
if ($table_role == 1)
header ("location: CHomePage.php"); // takes the user to the Customer Homepage
else if ($table_role == 2)
header ("location: HomePage.php"); // takes the user to the Staff Homeage
}//if
else
{
echo "<script>alert('Incorrect Username or Password!');</script>"; //Prompts the user
echo "<script>window.location.assign('login.php');</script>"; //redirects to login.php
}//else
{
$_SESSION['UserID'] = $userid;
}
}//if
mysqli_free_result($result);
mysqli_close($conn);
?>
Это моя домашняя страница. php
<div class="Main">
<?php
// You'd put this code at the top of any "protected" page you create
// Always start this first
session_start();
if ( isset( $_SESSION['UserID'] ) ) {
// Grab user data from the database using the user_id
// Let them access the "logged in only" pages
} else {
// Redirect them to the login page
header("Location:Login.php");
}
?>
This is the home page
<img src="images/homepic.jpg" width="1000" height="628" alt=""/>
</div>