'How to call variable from other php file
Why i can't call the variable from different php file? here are the fragments of my codes that has relationship with the message variable i just can't display the invalid username or pass into the index. php, the output was just it's refreshing from index.php if we put invalid data
code.php
<?php
session_start();
require_once "connection.php";
$message = ""
$role = "";
if (isset($_POST["btnLogin"])) {
$username = $_POST["username"];
$password = $_POST["password"];
$query = "SELECT * FROM tblUSer WHERE username='$username' AND password='$password'";
$result = mysqli_query($conn,$query);
if (mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_assoc($result))
{
if ($row["Role"] == "Admin")
{
$_SESSION['User'] = $row["Username"];
$_SESSION['role'] = $row["Role"];
header('Location: admin.php');
}
else
{
$_SESSION['User'] = $row["Username"];
$_SESSION['role'] = $row["Role"];
header('Location: user.php');
}
}
}
else
{
$message = "Invalid Username or Password";
header('Location: index.php');
}
}
?>
index.php
<?php
include "code.php";
?>
//i did not include other lines
<form action="code.php" method="POST">
<div class="form-group">
<label>Username:</label>
<input type="text" name="username" class="form-control" placeholder="Enter Username: ">
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" name="password" class="form-control" placeholder="Enter Password: ">
</div>
<p class="text-center" style="color: red;">
<?php echo $message; ?>
</p>
<div class="form-group">
<input type="submit" name="btnLogin" class="btn btn-primary" placeholder="Login">
</div>
</form>
Solution 1:[1]
When you call header('Location: index.php'); you are leaving the current PHP file so any of its contents will no longer be accessible in the page you arrive at.
In order to fix this, instead of setting $message to your desired value, use $_SESSION variables.
For more info on session variables: https://www.w3schools.com/php/php_sessions.asp
You can set $_SESSION['message'] to whatever you want and then access that variable from another page.
Make sure to add session_start(); to the very top of your PHP.
Edit: There's more to your issue than I first noticed. When you include code.php in index.php after you redirect there, you risk getting stuck in an endless loop if you trigger the else clause. If you trigger the initial if statement and not the else clause, then you are setting $message back to an empty string, therefore you won't be displaying anything on the page.
Edit 2: There's even more to the question than I realised. I think you just need to remove header('Location: index.php'); and you should be able to access the $message variable. I'm not sure at this point as my brain is completely lost now.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
