Adding a link when Admin is loged in in PHP - php

So I was able to make a code work where if the user is an Admin in the database, the link 'ADMIN' shows. However, when no one is logged in, it shows that part of the code to determine if the user is admin is undefined index.
How do I make it so that it doesnt show the undefined index when no one is logged in?
<?php
session_start();
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="HandheldFriendly" content="True">
<link rel="stylesheet" type="text/css" media="screen" href="css/masthead.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/styles.css" />
</head>
<body>
<nav>
<div class="brand">
<h1>HOME PAGE</h1></div>
<ul>
<li>BOOKS</li>
<li>STORIES</li>
<li>QUOTES</li>
<li>UPLOAD</li>
<li>REGISTER</li>
<li>CONTACT ME</li>
<?php
$dbserverName = "localhost";
$dbuserName = "root";
$dbpassword = "";
$dbname = "database";
$db = mysqli_connect( $dbserverName , $dbuserName , $dbpassword , $dbname );
$value = $_SESSION['u_id'];
$sql = "SELECT admin, user_id FROM users WHERE username='".$value."'";
$result = mysqli_query($db,$sql);
if ($row = mysqli_fetch_assoc($result)) {
$user_id = $row['user_id'];
$u_admin = $row['admin'];
if ($u_admin === "Y") {
print '<li>admin</li>';
}
}
?>
<?php
if (isset($_SESSION['u_id'])) {
print '<form action = "includes/logout.inc.php" method="POST">
<button type="submit" name="logout">LOGOUT</button>
</form>';
}
else {
print '<form action = "includes/login.inc.php" method="POST">
<button type="submit" name="logout">LOGIN</button>
</form>';
}
?>
</ul>
</nav>
<section class="sec1"></section>
<section class="sec2"></section>
</div>
</ul>
</nav>
</div>
</header>
<main container class="siteContent">
<!-- BEGIN CHANGEABLE CONTENT. -->`enter code here`
I am stuck....I have tried different if statements with a variable equal to true instead...but that doesnt work.
I forgot to add the the error is at when I run the code. It doesnt show when the user is logged in, just when no one is logged in.
$value = $_SESSION['u_id'];

You need to check if array values are set before using them. Something like this
$u_admin = isset($row['admin']) ? $row['admin'] : false
If you are using php 7, you can shorten this with the null coalescing operator
$u_admin = $row['admin'] ?? false
This assigns your variable if it's set, otherwise it assigns it as the second value.

Related

Session gets destroyed after page refresh

Login.php
<?php
session_start();
$server = "localhost";
$user = "...";
$pass = "...";
$database = "...";
$verbindung = mysqli_connect($server, $user, $pass, $database)
or die("Verbindung konnte nicht hergestellt werden.");
$Email = $_POST["Email"];
$Passwort = $_POST["Passwort"];
$sql = "SELECT passwort FROM accounts WHERE email = '".$Email."'";
$hashPasswort = mysqli_query($verbindung, $sql);
$VerifyHash = mysqli_fetch_assoc($hashPasswort);
if(password_verify($Passwort, $VerifyHash['passwort']))
{
session_regenerate_id();
$_SESSION['email'] = $Email;
echo "<script type='text/javascript'>
window.location.replace('...');
</script>";
}
else
{
echo '<script type="text/javascript">
window.location.replace("...");
</script>';
}
$return = mysqli_close($verbindung);
if (!$return) {
echo "<p>Die Verbindung mit dem Server konnte nicht geschlossen werden.</p>";
}
?>
Index.php
<?php
session_start();
if (!isset($_SESSION['email'])) {
header('Location: Login.php?login=loginRequired');
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=0.85">
<link rel="icon" type="image/png" href="../Bilder/favicon.ico"/>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Erste-Hilfe Kurs</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='../CSS/main.css'>
<link rel='stylesheet' type='text/css' media='screen' href='../CSS/index.css'>
</head>
<body>
<header>
<div class="container">
<img src="../Bilder/Litec.png" alt="Litec" class="logo">
<img src="../Bilder/RotesKreuz2.png" alt="Litec" class="logo">
<nav>
<ul>
<li><b><u>Home</u></b></li>
<li>Über uns</li>
<li>Anmeldung</li>
<li>Impressum</li>
<li>LOGOUT</li>
</ul>
</nav>
</div>
</header>
<label id="email"></label>
<?php echo("{$_SESSION['email']}"."<br />");?>
</body>
</html>
I made a Login script which opens, if the password is correct, the Index.php site. When first opening the Index.php site via the Login script everything works fine and the session is set. But after I refresh the page the sessions gets destroyed and is not set.
So how can I save the session, so it's not getting destroyed by refreshing the browser?
This line in your index.php destroys your session:
<li>LOGOUT</li>
^^^^^^^^^^^^^^^^^
To realize your logout process, you could link to another php file and do your session_destroy(); there - for example.

HTML doesn't load after PHP opening tag

Right now I'm coding this really simple user page but getting one problem that's bugging me and can't find out why it's happening.
When ever I would put <?php HTML will just stop loading from there.
<?php
session_start();
if (!isset($_SESSION["user"])) {
$logged_in = "no";
} else {
$username = $_SESSION["user"];
$logged_in = "yes";
}
include ('global.php');
?>
<head>
<title><?php echo $sitename; ?></title>
<link rel="stylesheet" type="text/css" href="css.css">
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="header">
<div class="header_content">
<div class="middle_logo">
<p><?php echo $sitename; ?></p>
</div>
</div>
</div>
<div class="under_header">
<?php
$id = htmlentites($_GET["id"]);
$get_user_data = mysqli_query ($dconnect, "SELECT * FROM user_data WHERE id='$id'");
if (mysqli_num_rows($get_user_data) < 2) {
header ("Location: index.php");
} else {
while ($row = mysqli_fetch_array($get_user_data)) {
echo $row["username"];
}
}
?>
<h1><?php echo $users_name; ?></h1>
</div>
When I look at the source code it ends at <div class="under_header">
The answer has already been found in the comment :
The line :
$id = htmlentites($_GET["id"]);
Contain an error and should be :
$id = htmlentities($_GET["id"]);
Thanks to #RiggsFolly and #JustOnUnderMillions.
You can now accept an answer and close the question.

reports page keeps redirecting me to login page

My reports.php page keeps redirecting me back to the login page even though i have supposedly logged into the website. I am not quite sure what i might be doing wrong here.
reports page:
<?php require_once('dbadmin.php');?>
<?php
session_start();
$user = $_SESSION['users'];
if(!isset($users)){
header("Location:admin_login.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>e</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<header><img src="images/eastersealsclevelogo.png" alt="Easter Seals Logo" width="445" height="300"</img> </header>
<nav>
<ul>
<li>Home</li>
<li>Run Sign-Up</li>
<li>Refer-a-Friend</li>
<li>Admin Login</li>
<li>Reports</li>
</ul>
</nav>
<h1>Reports</h1>
<table border="1" style="width:100%">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Address</th>
<th>City</th>
<th>State</th>
<th>Distance</th>
</tr>
<?php
include('dbuser.php');
$select = "SELECT `fname`, `lname`, `email`, `distance` FROM runner ORDER BY `lname`";
$result = mysql_query($connect, $select) or die ('Oops! '.mysql_error($connect));
if($rowcnt==0){
echo "<tr><td colspan=3>There are currently no results.</td</tr>";}
while($row = mysql_fetch_assoc($result)) {
echo '<tr><td>'.$row['fname'].'</td>';
echo '<td>'.$row['lname'].'</td>';
echo '<td>'.$row['email'].'</td>';
echo '<td>'.$row['distance'].'</td></tr>';
}
?> </table>
<footer></footer>
</body>
</html>
adminlogin page:
<?php require_once('dbadmin.php');?>
<?php
session_start();
if(isset($_POST['adminlogin'])) {
$username = trim($_POST['user']);
$password = trim($_POST['password']);
include('dbadmin.php');
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysql_query($sql) or die("Invalid query: ".mysql_error());
if(mysql_num_rows($result)==0) {
$confirm = '<h2 style="color:red;">Invalid Credentials!</h2>';
} else {
$_SESSION['user'] = $username;
$confirm = '<h2> Login Successful</h2>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>My Gaming Products Site</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<header><img src="images/eastersealsclevelogo.png" alt="Easter Seals Logo" width="445" height="300"/> </header>
<nav>
<ul>
<li>Home</li>
<li>Run Sign-Up</li>
<li>Refer-a-Friend</li>
<li>Admin Login</li>
<li>Reports</li>
</ul>
</nav>
<h1>Enter Your Login Information</h1>
<?php if(isset($confirm)) echo $confirm; ?>
<form method="post" name="adminlogin" id="adminlogin" title="adminlogin" action="admin_login.php">
<p>User: <br> <input type="text" name="user"></p>
<p>Password: <br><input type="password" name="password"></p>
<p><input type="submit" name="adminlogin" id="adminlogin" value="Login"></p>
</form>
</p>
<footer>| WDD420</footer>
</body>
</body>
</html>
I think it might be something with my reports page but i am not sure if it has anything to do with the login page either.
Try to make your script a bit more readable, I suggest with a function:
<?php
function is_loggedin()
{
return (!empty($_SESSION['users']));
}
session_start();
if(!is_loggedin()){
header("Location:admin_login.php");
exit;
}
?>
By doing $user = $_SESSION['users'] then checking if $user is set, that will always be true because you set it. You will want to check empty().
In your adminlogin.php page the session variable is $_SESSION['user']. But in reports.php page it checks for $_SESSION['users']. Change that to $_SESSION['user'] and change the variable name to $user from $users.
session_start();
$user = $_SESSION['user'];
if(!isset($user)){
header("Location:admin_login.php");
}
Try checking users by this :
session_start();
if(!isset($_SESSION['users']) && empty($_SESSION['users'])){
header("Location:admin_login.php");
}
try this for check the variable is set or not :
session_start();
if(isset($_SESSION['users']) && !empty($_SESSION['users'])) {
print_r($_SESSION['users']);
}
Try this to also to check => var_dump($_SESSION['users']);
Put session_start(); at the first line of your php page.
Note : Also keep in mind, you need to call session_start(); on each and every page if you are making use of session variables.

$_SESSION in PHP is always returning 1

I'm trying to develop a login system in PHP which has faculty_login.php which displays faculty_login_option.inc.php which has a login form and if $_SESSION['f_id'] is set it redirects to faculty_upload_option.php. where faculty details are fetched from faculty_table using $f_id = $_SESSION['f_id'] as the primary key.but $_SESSION['f_id'] is always returning 1 and user is logging in as the user whose f_id is 1.
<?php
//faculty login page.faculty_login.php
//if logged in show upload option/show login option.
require_once 'resources/core.inc.php';//session is set here
require_once 'resources/connect.inc.php';//init db connection
if(isset($_SESSION['f_id'])&&!empty($_SESSION['f_id'])){
require_once 'faculty_upload_option.inc.php';
}
else{
require_once 'faculty_login_option.inc.php';
}
?>
<?php
/* faculty_login_db.php
* Check if the faculty can login or the credentials are wrong.
*/
require_once 'resources/core.inc.php';
require_once 'resources/connect.inc.php';
if(isset($_POST['f_username'])&&isset($_POST['f_password'])){
if(!empty($_POST['f_username'])&&!empty($_POST['f_password'])){
$username = stripcslashes($_POST['f_username']);
$password = stripcslashes($_POST['f_password']);
$result = $conn->prepare("SELECT f_id FROM faculty_table WHERE f_username= :hjhjhjh AND f_password= :asas");
$result->bindParam(':hjhjhjh', $username);
$result->bindParam(':asas', $password);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
if($result->rowCount() == 1) {
$_SESSION['f_id'] = $rows ;
$_SESSION['f_username'] = $username;
header('Location:faculty_login.php');
}
else{
header('Location:faculty_login.php?username='.$username);
}
}
else{
header('Location:faculty_login.php');
}
}
else{
header('Location:faculty_login.php');
}
?>
<?php
/* faculty_login_option.php
* faculty login page. check if user exists/ use faculty_login_db.php
*/
?>
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>Home</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0 , maximum-scale=1">
<link rel="stylesheet" href="resources/loginstyle.css">
</head>
<body>
<?php
//<img alt="full screen background image" src="images/orange.jpg" id="full-screen-background-image" />
?>
<div id="back">Home</div>
<div id="header">
<h3>FACULTY LOGIN</h3><br>
</div>
<hr>
<div id="container">
<center>
<form action="faculty_login_db.php" method="post">
<input type="text" onFocus="if(this.value=='Username'){this.value=''}" name="f_username" class="buttons" value="<?php
if(isset($_GET['username']))
{
echo $_GET['username'];
}else{echo 'Username';}
?>"><br>
<input type="password" onFocus="if(this.value=='Password'){this.value='';}" name="f_password" class="buttons" value="Password"><br>
<input type="submit" value="Login" class="lbutton">
</form>
</center>
<?php
if(isset($_GET['username'])){
?>
<div id="errormsg">Username or password is invalid.</div>
<?php
}
?>
</body>
<?php
/* this is faculty_upload_option.inc.php
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
require_once 'resources/core.inc.php';
require_once 'resources/connect.inc.php';
if(isset($_SESSION['f_id'])&&isset($_SESSION['f_username'])&&!empty($_SESSION['f_id'])){
$f_id=trim(isset($_SESSION['f_id']));
if(!empty($f_id)){
$result = $conn->prepare("SELECT * FROM faculty_table WHERE f_id=:id");
$result->bindparam(':id', $f_id);
$result->execute();
$rows = $result->fetchAll();
foreach($rows as $db_rows){
$f_username = $db_rows['f_username'];
$category = $db_rows['category'];
$branch = $db_rows['branch'];
}
//page which should be displayed if user logs in.?>
<html>
<head><title><?php echo $f_username; ?></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0 , maximum-scale=1">
<link href='http://fonts.googleapis.com/css?family=Indie+Flower|Yanone+Kaffeesatz' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="resources/upload_style.css">
</head>
<body><div id="parent">
<div id="header">
<img src="images/no-profile-image.png" width="30%" id="noimg">
<span id="addfont"><h1><?php echo $f_username;?></h1></span>
<h2><?php echo $category;?></h2>
<p><?php echo $branch;?></p>
<center><div class="buttons" id="left">Home</div><div class="buttons" id="right">Logout</div></center>
</div>
Are you destroying session correctly on logout? Are you setting session id before hitting the condition somewhere? What is the value before hitting the comparion condition?

Trying to get a PHP button to delete MySQL rows

EDIT: Added the whole code for viewProblems, with the actual credential information just ***.
I've been trying to do this all day and I can't figure it out. What I want is a button at the end of each row (the button shows up correctly) that allows me to delete that row from the MySQL database and the page (doesn't delete anything though). The code I have is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>View Problems</title>
<!-- Bootstrap core CSS -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="well">
<div class="container">
<div class="page-header">
<h1>Jimmy's Laundry</h1>
</div>
<ol class="breadcrumb">
<li>Home</li>
<li>Login</li>
<li>Admin page</li>
</ol>
</div>
</div>
<?php
$servername = "***";
$username = "***";
$password = "***";
$dbname = "***";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT problem_id, machine_id, description FROM tbl_problem";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
echo '<table class="table table-hover"><tr><th>Problem ID</th><th>Machine Number</th><th>Problem Description</th><th> </th></tr>';
while($row = $result->fetch_assoc())
{
echo "<tr><td>" . $row['problem_id']. "</td><td>" . $row['machine_id']. "</td><td>" . $row['description']. "</td><td><form action='deleteProblem.php?name=" . $row['problem_id']."' method= 'post'><input type='hidden' name='id' value=".$row['problem_id']."><input class ='btn btn-danger' type='submit' name='submit' value='Resolved?'></form></td></tr>";
}
echo "</table>";
}
else
{
echo "There are no problems! :)";
}
?>
</table>
</body>
For my main page, viewProblems.php. My deleteProblem.php page is as follows:
<?php
$query= "DELETE FROM tbl_problem WHERE problem_id={$_POST['id']}";
mysql_query ($query);
if (mysql_affected_rows() == 1)
{
echo "<strong>Row has been deleted</strong>"
}
else
{
echo "<strong>Deletion Failed</strong>"
}?>
I've been browsing this site and Google, and I'm trying to get it to work, but it just won't. The page loads the table correctly, but when I click the button, it takes me from website/viewProblems.php to website/deleteProblem.php?name=9(or 10, 11, 12, 13, depending on which button I press) but the page is just white space and the database doesn't get updated.
Any help would be appreciated.
P.S. I know that mySQL_ methods are dated, but we have to use them.
The script that deletes the row is a separate script that is executed in a separate request. Therefor, it is completely isolated from the request that generated the page and you will have to make a new database connection if you want to query or delete data.
In your current situation, you don't make a connection, so that's why the delete statement fails.

Categories