I have 2 pages. I need on "addproduct.php" to check whether the user is logged in as an admin. I have a login script. Apologies if this is a silly question but im brand new to PHP.
I want a user who reaches this page who is not logged in as an admin ('isadmin' is a row in the user database) to be redirected to the login page, and when someone is logged in as an admin for the page to display.
Login.php;
<?php
session_start();
$un = $_POST["username"];
$pw = $_POST["password"];
$conn = new PDO ("mysql:host=localhost;dbname=assign026;", "assign026",
"ziSietiu");
$results = $conn->query("select * from users where username='$un' and
password='$pw'");
$row = $results->fetch();
if($row == false)
{
echo "Incorrect password!";// There were matching rows
}
else
{
$_SESSION["gatekeeper"] = $un;
$_SESSION["isadmin"] = $row["isadmin"];
header ("Location: index.php");
}
?>
And addproduct.php
<?php
session_start();
?>
<?php
// Test that the authentication session variable exists
if(!isset($_SESSION["isadmin"]) || $row["isadmin"] == 1)
{
header('Location: login.html');
exit();
}
else
{
echo ($_SESSION["isadmin"]);
}
?>
<div>
<h2>Add new product</h2>
<form method="post" action="addproductscript.php">
<p>Insert product here</p>
<input type="text" name="name" placeholder="name">
<input type="text" name="manufacturer" placeholder="manufacturer">
<input type="text" name="description" placeholder="description">
<input type="text" name="price" placeholder="price">
<input type="text" name="stocklevel" placeholder="stocklevel">
<input type="text" name="agelimit" placeholder="agelimit">
<input type="submit" value="Submit">
</form>
</div>
Based on your code if(!isset($_SESSION["isadmin"]) || $row["isadmin"] == 1), the $row["isadmin"] is not defined thus it don't have any value.
What you can do is if(!isset($_SESSION["isadmin"]) || $_SESSION["isadmin"] == 1)
Related
I created a simple login form. When I enter the correct username and password, it is always displaying the access denied message.
verify.php:
<?php
session_start();
$conn = mysqli_connect('localhost','root','') or die(mysqli_error());
mysqli_select_db($conn,'maindata') or die(mysqli_error($conn));
$uname=$_POST['username'];
$pass=$_POST['password'];
$password = md5($pass);
$result = mysqli_query($conn,"select * from users where username='$uname' and password='$password'")
or die("Could not execute the select query.");
$row = mysqli_fetch_assoc($result);
if(is_array($row) && !empty($row))
{
$validuser = $row['username'];
$_SESSION['valid'] = $validuser;
}
else
{
echo "<center></h1>Access Denied</h1></center>"."<br />";
echo "<center></h6>Please wait while you are redirected in 3 seconds</h6></center>"."<br />";
header('Refresh: 3; url=login.html');
}
if(isset($_SESSION['valid']))
{
header("Location:index.html");
}
login.html:
<?php
session_start();
if(isset($_SESSION['valid'])){
header("Location:index.html");
}
else
{
header("location:login.html");
}
?>
<form method="post" action="verify.php" class="login" class="contact_form">
<p>
<label for="login">Email:</label>
<input type="text" name="username" placeholder = "Enter Username Here...">
</p>
<p>
<label for="password">Password:</label>
<input type="password" name="password" placeholder = "*******">
</p>
<p class="login-submit">
<button type="submit" class="login-button">Login</button>
</p>
<p class="forgot-password">Forgot your password?</p>
</form>
You'r code loops it self, Login.html checks if a user is logged in ( which they arrent because they cant login ) and redirects them from Login.html to Login.html meaning that you never enter your php code. You should not check if the user is already logged in when trying to access the login page.
Also you should consider making a file to check if the user is logged in, it could be something like this:
checkloggedin.php
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if($_SESSION['loggedin'] == false)
{
die(header("Location: ./index.php"));
}
?>
When you need to check if a user is logged in you can just start your pages off with:
<?php
include"checkloggedin.php"
?>
I am currently organising my files into appropriate folders and a problem has arisen. Before changing the code to organise the files everything worked. Now whenever I try to log in, instead of redirecting to 'Staff/staff.php', it redirects to 'Staff/index.php'.
The code is as follow:
<?php
session_start();
include("connectdb.php");
//if the form has been submitted
if (isset($_POST['submitted'])){
//get the information out of get or post depending on your form
$username = $_POST['username'];
$password = $_POST['password'];
global $db;
//sanitise the inputs!
$safe_username = $db->quote($username);
//run a query to get the user associated with that username
$query = "select * from user where username = $safe_username";
$result = $db->query($query);
$firstrow = $result->fetch(); //get the first row
if (!empty($firstrow)) {
//check the passwords, if correct add the session info and redirect
$hashed_password = md5($password);
if ($firstrow['password'] == $hashed_password){
$_SESSION['id'] = $firstrow['userID'];
$_SESSION['username'] = $firstrow['username'];
$_SESSION['fname'] = $firstrow['first_name'];
$_SESSION['lname'] = $firstrow['last_name'];
$_SESSION['staff'] = $firstrow['staff'];
if($firstrow['staff'] == 1) {
header("Location:Staff/staff.php");
exit();
} else {
//echo "Success!";
header("Location:Customer/customer.php");
exit();
}
} else {
echo "<h1>Error logging in, password does not match</h1>";
}
} else {
//else display an error
echo "<h1>Error logging in, Username not found</h1>";
}
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="CSS/theme.css">
</head>
<body>
<h1 class="register-title">Aston Animal Sanctuary</h1>
<div class="register">
<!--<form method="link" action="staff.php">
<input type="submit" value="Staff Login">
</form>-->
<form action="index.php" method="post">
<input type="text" class="register-input" name="username" placeholder="Username">
<input type="password" class="register-input" name="password" placeholder="Password">
<input type="submit" value="Login" class="register-button">
<input type="hidden" name="submitted" value="TRUE" />
</form>
<form method="link" action="register.php">
<input class="register-button" type="submit" name="register" value="Register">
</form>
<div>
<!--Test-->
</body>
</html>
<?php include('View/footer.html'); ?>
Is the header the problem?
EDIT
The same thing happens with my logout file. It redirects to 'Staff/logout.php' instead of '../logout.php'. It worked before I started organising the files.
The code for logout.php:
<?php
session_start(); //get the previous session info
session_destroy(); //destroy it
header("Location: ../index.php"); //redirect back to the start
?>
Have you tried:
header("Location: ./staff/staff.php");
and:
header("Location: ./customer/customer.php");
These are the four pages which include the code for sessions. when i run the sign_up.php page an error comes up stating the page cannot be displayed. So the sessions are giving me an problem. I have included the session code on each page however i believe the problem is in the header(location:........); So any solutions please.
sign_up.php
<?php
//session_start();
//if (!isset($_SESSION["user_login"])) {
// header("Location: sign_up.php");
//} else {
// $username = $_SESSION["user_login"];
//}
?>
<!----------------------------------------------------------------------------------------------------->
<h1> Sign Up </h1>
<hr>
<div class = "user_type">
<form action="sign_up.php" method="POST" enctype="multipart/form-data">
<input type="radio" value="Student" id="radioOne" name="account" checked/>
<label for="radioOne" class="radio" chec>Student </label>
<input type="radio" value="Landlord" id="radioTwo" name="account" />
<label for="radioTwo" class="radio">Landlord</label>
<hr/>
<div class = "gender_options">
<input type="radio" value="Male" id="male" name="gender" checked/>
<label for="male" class="radio" chec>Male</label>
<input type="radio" value="Female" id="female" name="gender" />
<label for="female" class="radio">Female</label>
</div>
<input type="text" name="name" id="name" placeholder="Full Name" required/> <br/><br/>
<input type="email" name="email" id="name" placeholder="Email" pattern="[a-z0-9._%+-]+#aston.ac.uk" required/> <br/><br/>
<input type="text" name="password" id="name" placeholder="Password" required/><br/><br/>
<input type="text" name="password2" id="name" placeholder="Retype Password" required/><br/><br/>
By clicking Sign Up, you agree on our terms and condition. <br/><br/>
<input type="submit" name="submit" value="Sign Up"/>
</form>
</div>
<hr>
<!---- log in code--->
<?php
enter code here
if (isset($_POST["user_login"]) && isset ($_POST["user_pass"])){
// formatting field via reg replace to ensure email and password only conisists of letters and numbers preg_replace('#[^A-Za-z0-9]#i','',
$login_user = $_POST["user_login"];
$login_password = $_POST["user_pass"];
// password is encryted in DB (MD5) therefore user inputted password will not match encryted password in DB - we have to assign new var
$decrypted_password = md5($login_password);
// Query which finds user (if valid) from DB - Achieving authentication via username and password
$user_query = mysqli_query($connect, "SELECT * FROM users WHERE email = '$login_user' AND password = '$decrypted_password' AND closed = 'no' LIMIT 1");
$check_user = mysqli_num_rows($user_query); // checking to see if there is infact a user which those credentials in the DB
if ($check_user==1){
while ($row = mysqli_fetch_array($user_query)){
$id = $row['user_id'];
}
enter code here
// if the user credentials are correct, log the user in:
$_SESSION["user_login"] = $login_user;
header( "Location: profile_student.php" ); // refresh page
exit;
// if user row does not equal 1 ...
//exit;
} else {
echo "<div class='wrong_login'>
<p> Email or password is incorrect, please try again. </p>
</div>";
}
}
?>
<h1> Log In </h1>
<hr>
<div class ="login_form">
<form action="sign_up.php" method="POST">
<input type="text" name="user_login" placeholder="Email" pattern="[a-z0-9._%+-]+#aston.ac.uk" required/><br/><br/>
<input type="text" name="user_pass" placeholder="Password" required/> <br/><br/>
<input type="submit" name="login_submit" value="Log In"/>
</form>
</div>
</div>
home.php
<?php
session_start();
if (!isset($_SESSION["user_login"])) {
header("Location: profile_student.php");
} else {
$username = $_SESSION["user_login"];
}
include ("connect.php");
echo "Hello,";
echo"<br/> Would you like to logout? <a href = 'logout.php'>LogOut</a>";
?>
profile_student.php
This is the page for when the user logs in and this page will allow them to access their information etc.
<?php
session_start();
if (!isset($_SESSION["user_login"])) {
header("Location: sign_up.php");
} else {
$username = $_SESSION["user_login"];
}
include ("includes/connect.php");
?>
logout.php
this is the log out code for my website
<?php
session_start();
session_destroy();
unset($_SESSION);
session_write_close();
header( "Location: ../index.php" );
die;
?>
Instead of doing the session_start in each page, make a common.php file and include this file in all the required pages. Also, you need to make sure there is no white space before session is started, otherwise it would throw the header already sent error!
You are true, the problem is the header.
You are creating an infinite loop saying : you come on sign_up ? If $_SESSION['user_login'] doesnt exist, go to sign_up.
And it repeats over and over again. Because $_SESSION['user_login'] cant exist first time you come on sign_up.
So just do this : on your sign_up page.
<?php
session_start();
And so remove the if / else condition.
I have a login script with a admin thats redirected to his own page dashboardadmin.php.Then i have a page called dashboarduser.php. The users have its own page dashboarduser.php. When the user comes to dashboarduser.php it should only show their project. Now its showing all of the projects. I have created the omproject.php that show the project. So what i want is when user login is should come to dashboarduser.php and only show their projct.
index.php
<?php
if (isset($_GET['error'])) {
echo '<p class="error">Error!</p>';
}
?>
<form action="includes/process_login.php" method="post" name="login_form">
<label for="email"> Email:</label> <input type="email" id="email" name="email" />
<label for="password">Password: </label> <input type="password"
name="password"
id="password"/>
<input type="submit"
value="Login"
onclick="formhash(this.form, this.form.password);" />
</form>
process_login.php
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start(); // Our custom secure way of starting a PHP session.
if (isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
$password = $_POST['p']; // The hashed password.
if (login($email, $password, $mysqli) == true) {
// Login success
header('Location: ../dashboardadmin.php');
} else {
// Login failed
header('Location: ../index.php?error=1');
}
} else {
// The correct POST variables were not sent to this page.
echo 'Invalid Request';
}
?>
sql DB
members
project
dashboarduser.php
$sql= "SELECT pid, project_name, image, image_type FROM project";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
//$type= "Content-type:".$row['image_type'];
//header ($type);
echo "<form action='omprojekt.php' method='post'><button name='submit'>
<div>
<img src=pic.php?pid=".$row['pid']." width=100px height=100px/>"." ".$row['project_name']."
<input type='hidden' name='pid' value='".$row['pid']."'>
<input type='hidden' name='project_name' value='".$row['project_name']."'>
</div>
</button></form>";
}
}
else {
echo "0 results";
}
omproject.php
<?php
$val = (isset($_POST['pid']) && isset($_POST['project_name'])) ?
"<img src=pic.php?pid={$_POST['pid']} width=100xp height=100xp/> {$_POST['project_name']}" : '';
if(isset($_POST['submit'])){
echo "$val";
}
?>
You don't have a link between your project table and your user table. You'll need to add a column in your project table which refers to the user that owns the project. Let's name that table "user_id" for now.
After login you should have the id of the user that's logged in. you can use that to get their project. Then to fetch their projects you can use the following sql query:
$sql= "SELECT pid, project_name, image, image_type FROM project WHERE user_id =" . $loggedInUserId;
I am trying to do a login with MySQL, but it's not working. Basically I'm trying to check the login and password posted against my DB, but it's not working for some reason. Could someone give me a hint?
login.php
include "conexao.php";
$result = mysql_query("SELECT * FROM usuario WHERE login = '".$_POST['login']."' AND senha = '".$_POST['senha']."'") or die (mysql_error());
while ($row = mysql_fetch_assoc($result)) {
session_start();
if ($_POST['login'] && $_POST['senha']) {
if ($row['login'] == $_POST['login'] && $row['senha'] == $_POST['senha']) {
$_SESSION['login'] = $row['login'];
$_SESSION['senha'] = $row['senha'];
header("Location: index.php");
} else {
unset ($_SESSION['login']);
unset ($_SESSION['senha']);
header("Location: login2.php?i=n");
}
}
}
HTML form
<form method="post" action="login.php" class="cbp-mc-form" autocomplete="off">
<label for="login">Login</label>
<input type="text" name="login" id="login" /><br />
<label for="senha">Senha</label>
<input type="password" name="senha" id="senha" /><br />
<center><input class="cbp-mc-submit" type="submit" value="Login""/></center>
</form>
Dear Brother try the following code, (I edited your code)
I hope it will work in your case, but if you're using the same code for production, than please take care of the Sanitization.
the code I edited for you is as follows (if it still doesn't work, than there might be some error in your database connection).
The PHP Script:
<?php
session_start(); // better to start the session in the begining,
//in some cases it doesn't work in the mid of the document'
include 'conexao.php';
if (isset($_POST['login']) && isset($_POST['senha'])) // check if both the form fields are set or not
{
// Values coming from the user through FORM
$login_form = $_POST['login'];
$senha_form = $_POST['senha'];
// query the database only when user submit the form with all the fields filled
$result = mysql_query("SELECT * FROM usuario WHERE login='$login_form' AND senha='$senha_form'") or die (mysql_error());
while ($row = mysql_fetch_assoc($result))
{
// values coming from Database
$login_db = $row['login'];
$senha_db = $row['senha'];
}
// compare the values from db to the values from form
if ($login_form == $login_db && $senha_form == $senha_db)
{
// Set the session only if user entered the correct username and password
// it doesn't make sense to set session even if the user entered wrong values
$_SESSION['login'] = $login_db;
$_SESSION['senha'] = $senha_db;
header("Location: index.php");
}
else
{
header("Location: login2.php?i=n");
}
}
?>
The HTML: (exactly your html copied)
<form method="post" action="login.php" class="cbp-mc-form" autocomplete="off">
<label for="login">Login</label>
<input type="text" name="login" id="login" /><br />
<label for="senha">Senha</label>
<input type="password" name="senha" id="senha" /><br />
<center><input class="cbp-mc-submit" type="submit" value="Login""/></center>
</form>
from PHP Header not redirecting
I added ob_start(); on the very first line and it worked.