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;
Related
I've been stuck on this issue for 3 days now. I'm trying to make a login form (I've already created a register form) and the database is working too. But now while I'm trying to make the login form, I've noticed that PHP only takes the last row from the database.
As you can clearly see in the first picture, my database has 3 records.
But when I try to log in on my account, it only lets me log in to the most recently created account, and not the others. Here's my current code:
<div class="login-form">
<form method="POST">
<p style="float:left;">
<input type="email" class="login-input" maxlength="40" name="login-email" id="login-email" placeholder="email" required><span style="color: red;"> *</span><br><br>
<input type="password" class="login-input" maxlength="32" name="login-passw" id="login-passw" placeholder="password" required><span style="color: red;"> *</span><br><br>
<input type="submit" class="btn" name="login-btn">
</p>
<?php
$email = $_POST["login-email"];
$passw = $_POST["login-passw"];
$encrypted_passw = md5($passw);
$sql = "SELECT id, email, passw FROM users";
$result = $db->query($sql);
// if (isset($_POST["login-btn"])) {
// if ($_POST["login-email"] == $result["email"]) {
// echo "<p>Logged in</p>";
// } else {
// echo "<p>wrong</p>";
// }
// }
while ($row = $result->fetch_assoc()) {
$get_email = $row["email"];
$get_usr = $row["username"];
$get_passw = $row["passw"];
}
if (isset($_POST["login-btn"])) {
if ($_POST["login-email"] == $get_email && $encrypted_passw == $get_passw) {
echo "<p>Logged in</p>";
} else {
echo "<p> wrong</p>";
}
}
?>
</form>
</div>
Try this. First of all I would place the php code above the HTML.
You only need to listen the post param login-btn. Read the other post data into vars and confirm its there before proceeding.
When you poll the DB you dont need to read every record (imagine you have thousands of records, you wouldn't want to pull them all down). Just filter for the supplied email with a where clause.
If the email exists it will return a result with the hashed password. Verify this matches and you are good to go.
The issue you're having where the last record in the db is beiung used is becuase in your loop, you are overwriting the var $get_email each time.
<?php
if (isset($_POST["login-btn"])) {
$email = (isset($_POST["login-email"]) ? $_POST["login-email"] : '');
$passw = (isset($_POST["login-passw"]) ? $_POST["login-passw"] : '');
if($email != "" && $passw != ""){
$encrypted_passw = md5($passw);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
$stmt = $mysqli->prepare("SELECT email, passw FROM users where email = ?");
$stmt->bind_param($email);
$stmt->execute();
while ($row = $result->fetch_row()) {
$get_passw = $row["passw"];
if($encrypted_passw == $row['passw']){
echo "logged in";
}else{
echo 'no match';
}
}
}
}
?>
<div class="login-form">
<form method="POST">
<p style="float:left;">
<input type="email" class="login-input" maxlength="40" name="login-email" id="login-email" placeholder="email" required><span style="color: red;"> *</span><br><br>
<input type="password" class="login-input" maxlength="32" name="login-passw" id="login-passw" placeholder="password" required><span style="color: red;"> *</span><br><br>
<input type="submit" class="btn" name="login-btn">
</p>
</form>
</div>
Gottem! I was using array's instead of values
<?php
session_start();
include_once "../php/db_connect.php";
if (isset($_POST["login-btn"])) {
$email = $_POST["email"];
$passw = $_POST["passw"];
$encrypted = md5($passw);
$sql = "SELECT * FROM users WHERE email = '". $email ."'";
$result = $db->query($sql);
$get_result = $result->fetch_assoc();
if ($encrypted == $get_result["passw"]) {
echo "<p>Logged in!</p>";
$_SESSION["username"] = $get_result["username"];
$_SESSION["id"] = $get_result["id"];
$_SESSION["email"] = $get_result["email"];
Header("Location:../../../");
} else {
echo "<p>Error</p>";
}
}
?>
change your query to this
"SELECT id, email, passw FROM users where email='".$row["email"]."'
and password= '".$row["password"]."'"
you do not need to use foreach for all rows this query return only one row that you need
I am new to php. I could not log in either from the user or the admin. How do make it so the user could log in and will be redirected to index.php, and once the admin login will be redirected to admin.php.
I did some research with youtube and could not find anything helpful on what I need.
<form action="login.php" method="post">
<input class="space" name="username" type="text"
placeholder="Username/E-
mail" required="required"></input>
<br />
<input class="space" name="password" type="password"
placeholder="Password" required="required"></input>
<br />
<input type="submit" class="log-btn" value="Login" />
<button type="button" class="log-btn" onclick="return
abc(1,'reg.html')">Register</button>
</form>
This is the database table:
I had also included the admin username and password in the database so admin does not have to register
<?php
include ("conn.php");
session_start();
$sql="SELECT * FROM user WHERE email = '".$_REQUEST['username']."' and
password = '".$_REQUEST['password']."' or username =
'".$_REQUEST['username']."' and password = '".$_REQUEST['password']."'
LIMIT 1";
$result=mysqli_query($con,$sql);
if (mysqli_num_rows($result) <= 0) {
$cred = mysqli_fetch_row($result);
$_SESSION['user'] = $cred[1];
echo "<script>window.location.href='index.php';</script>";
} else {
echo "<script>window.location.href='index.php?msg=Invalid+Credential';
</script>";
}
if ($row=mysqli_fetch_array($result)) {
$_SESSION['role']=$row['user_role'];
}
if ($row['user_role']==="1"]) {
echo "<script>alert('Welcome back admin!');";
echo "window.location.href='admin.html';</script>";
}
I expect that the user will be able to login and will be redirected to the index.php and the admin will be able to login as well as but will be redirected to the admin.php. But what I am seeing a white page and some error code on line 20. I know my if-else statement has some issue but not sure on how to fix it to be working
Your login.php should be like this:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "root", "dbpass", "dbname"); // make seperate file
if($_POST){
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $_POST['username'], $_POST['password']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
session_start();
while($row = $result->fetch_assoc()) {
if($row['role'] == 1){
$_SESSION['message'] = $row['username'];
header("Location: admin.php");exit();
}else{
$_SESSION['message'] = $row['username'];
header("Location: index.php");exit();
}
}
}else{
echo "Wrong Credentials";
}
$stmt->close();
}
?>
<form action="login.php" method="post">
<input class="space" name="username" type="text"
placeholder="Username/E-
mail" required="required"></input>
<br />
<input class="space" name="password" type="password"
placeholder="Password" required="required"></input>
<br />
<input type="submit" class="log-btn" value="Login" />
<button type="button" class="log-btn" onclick="return
abc(1,'reg.html')">Register</button>
</form>
And For Both page admin.php and index.php you check active session using $_SESSION['message'].
In that you will get the name of the user.
NOTE: Please do not use store plain text passwords! Please use PHP's password_hash() for password security.
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)
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 apologize for what will probably be a lengthy post.. I'm fairly new with PHP and trying to get a working registration / log in system for users on my website for a final project.
The log in system was working for registered users until I modified the way registration is validated. I need to have some angular on the website for the project requirements so I created a registration page that looks like this :
register.php
<form ng-app="myApp" ng-controller="validateCtrl" name="myForm" method="post" action= "<?php htmlentities($_SERVER['PHP_SELF'])?>" novalidate>
<p>Username:<br>
<input type="text" name="myusername" value="myusername" ng-model="myusername" required>
<span style="color:red" ng-show="myForm.myusername.$dirty">
<span ng-show="myForm.myusername.$error.required">Username is required.</span>
</span>
</p>
<p>Password:<br>
<input type="password" name="mypassword" value="mypassword" ng-model="mypassword" required>
<span style="color:red" ng-show="myForm.mypassword.$error.required && myForm.mypassword.$dirty">Password Required</span>
</p>
<p>Email:<br>
<input type="email" name="myemail" value="myemail" ng-model="myemail" required>
<span style="color:red" ng-show="myForm.myemail.$dirty && myForm.myemail.$invalid">
<span ng-show="myForm.myemail.$error.required">Email is required.</span>
<span ng-show="myForm.myemail.$error.myemail">Invalid email address.</span>
</span>
</p>
<p>
<input type="Submit" name="Submit" value="Submit" ng-disabled="myForm.myusername.$invalid || myForm.myemail.$invalid || myForm.mypassword.$invalid">
</p>
if (isset($_POST['Submit'])) { //form submission
$newusername = sanitize($_POST['myusername']); //sanitize username, email, and password
$newpassword = sanitize($_POST['mypassword']); // encrypt password
$newemail = sanitize($_POST['myemail']);
$sqlname = "SELECT username FROM users WHERE username = '".$newusername."'";
$result1 = $conn->query($sqlname);
if ($result1->num_rows > 0) //make sure username does not exist
{
echo "
<script>
alert('Username already taken. Try again.')
</script>
";
}
$sqlemail = "SELECT email FROM users WHERE email = '".$newemail."'"; //make sure email does not exist
$result2 = $conn->query($sqlemail);
if ($result2->num_rows > 0)
{
echo "
<script>
alert('That email is already in use.')
</script>
";
}
if (($result1->num_rows < 1) && ($result2->num_rows < 1)) //if no results for username or email query register user
{
$sqlinsert = "INSERT INTO users SET username = '".$newusername."', password = '".$newpassword."', email = '".$newemail."'";
$conn->query($sqlinsert);
echo "".$newusername." has registered. ";
}
};
?>
The registration is working just fine. If I register a user named 'testuser' with 'testpassword' it shows up in the user database.
The issue is now any accounts created with the angular registration are not able to log in. (Accounts created before adding the angular work fine)
The log in pages look like this:
Login.php
<form id='form1' name='form1' method='post' action='php/checklogin.php'>
<form role='form'>
<div class='form-group'>
<label for='username'>Username</label><input type='text' class='form-control' id='myusername' name='myusername'>
</div>
<div class='form-group'>
<label for='password'>Password</label><input type='password' class='form-control' id='mypassword' name='mypassword'>
</div>
<button type='submit' id='Submit' name='Submit' value='Submit' class='btn btn-default'>Submit</button>
</form>
checklogin.php
<?php
require("connect.php");
$myusername = $_POST['myusername'];
$mypassword = $_POST['mypassword'];
$query = $conn-> prepare("SELECT * FROM users WHERE username ='".$myusername."' AND password='".$mypassword."'");
$query->execute();
$query->store_result();
$result = $query->num_rows;
if ($result < 1 ){
//header('Refresh: 2;url=..\login.php');
echo "<span style='color: red'>Wrong Username or Password. Try again.</span>";
var_dump($myusername, $mypassword);
}
else if ($result > 0) {
session_start();
$_SESSION['myusername']= $myusername;
header('Refresh: 0;url=..\index.php');
}
else {
echo "oops, there was an error";
}
?>
For some reason I am now getting invalid username / password for any account I create when I try to log in with it.
The var dump shows the variable values are being set - ie (user="testuser" password="testpassword") and the user is in the database however the query is failing.
Any help would be appreciated! Thank you!