Question
I need to write PHP code to edit my pages so the link in the home page that says Not available unless you are Admin,
I need to write PHP code to edit my pages so the link in the home page that says "Not available unless you are Admin", can only be accessed by admin. The admin credentials are username ("admin") and password ("dcsadmin01"). Also please note that all credentials are saved in a text file (users.txt). Please have a look on the pages below:
login.php
// session start
session_start();
if(isset($_POST['login'])) // it checks whether the user clicked login button or not
{
$user = $_POST['username'];
$pass = $_POST['password'];
if(isset($_POST["username"]) && isset($_POST["password"])){
$file = fopen('users.txt', 'r');
$good=false;
while(!feof($file)){
$line = fgets($file);
$array = explode(";",$line);
if(trim($array[0]) == $_POST['username'] && trim($array[1]) == $_POST['password']){
$good=true;
break;
}
} if($good){
$_SESSION['username'] = $user;
echo "";
}else{
echo "Invalid UserName or Password";
}
fclose($file);
}
}
?>
home.php
// session starts with the help of this function
session_start();
$userid='';
//check session is set or not
if(isset($_SESSION["username"])){
//get the username and store in variable
$userid=$_SESSION["username"];
}
else{
header("Location:login.php");
}
?>
Welcome:
Logout
DTresults,
P1results, PfPresults Not available unless you are Admin
admin.php
session_start();
$userid='';
//check session is set or not
if(isset($_SESSION["username"])){
//get the username and store in variable
$userid=$_SESSION["username"];
}
else{
header("Location:login.php");
}
// if submit form we get data from $_POST method
if(isset($_POST["username"]) && isset($_POST["password"]))
{
// check if user file exist.
$file=fopen("users.txt","r");
$finduser = false;
while(!feof($file))
{
//get the data in line
$line = fgets($file);
// split username and password and store in array which is save in users.txt file
$array = explode(";",$line);
if(trim($array[0]) == $_POST['username'])
{
$finduser=true;
break;
}
}
fclose($file);
// register user or pop up message
if( $finduser )
{
echo $_POST["username"];
echo ' existed! ';
include 'admin.php';
}
else
{
// save data in text file
$file = fopen("users.txt", "a");
fputs($file,$_POST["username"].";".$_POST["password"]." ");
fclose($file);
// print register username
echo $_POST["username"];
echo " registered successfully!";
}
}
?>
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started