prepared statement executes, but i can't fetch the results - php

I'm was doing this tutorialHow to create a login system in PHP
I'm trying to use an IF statement to check if to set the session id. The current allows a user to log in and echos the current session id. When I purposely enter a wrong password, the code should echo a message, but it doesn't do anything. In addition, I am unable to use the logout button to kill the session.
Here is my login page
<?php
session_start();
//include 'dbh.php';
//probably do not need this can write connection in this file too
$conn = new PDO('mysql:host=localhost;dbname=testtable', 'root', '');
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
if(!$conn){
die("Connection is fubar yo!!! ");
}
$uid = $_REQUEST['uid'];
$pwd = $_REQUEST['pwd'];
$sql = "SELECT * from user WHERE uid='$uid' AND pwd='$pwd'";
$result = $conn->prepare($sql);
$result->execute();
if(!$row = $result->fetch(PDO::FETCH_ASSOC)){
echo("Your username or Password is wrong");
} else {
echo("hey man..it works");
$_SESSION['id'] = $row['id'];
}
header("Location: fakelogin.php");
?>
Here is my logout page.
<?php
session_start();
session_destroy();
header("Location: fakelogin.php");
?>
here is the main page that contains login, signup and logout buttons.
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Look ma, no hands!</title>
</head>
<body>
<form action="login.php" method="POST">
<input type="text" name="uid" placeholder="Enter username"><br>
<input type="password" name="pwd" placeholder="Enter password"><br>
<button type="submit" id="login">LOGIN</button>
</form>
<?php
echo("testing");
if(isset($_SESSION['id'])){
echo($_SESSION['id']);
} else {
echo("You are not logged in");
}
?>
<br><br><br>
<form action="signup.php" method="POST">
<input type="text" name="first" placeholder="Enter first name"><br>
<input type="text" name="last" placeholder="Enter last name"><br>
<input type="text" name="uid" placeholder="Enter username"><br>
<input type="password" name="pwd" placeholder="Enter password"><br>
<button type="submit" id="sbt">SIGN UP HERE YO!</button>
</form>
<br><br><br>
<form>
<button action="logout.php">LOG OUT</button>
</form>
</body>
</html>

Based on the code you have provided, you will always return to the login page.
When logged in, the string below login button will say testing followed by your user account id.
Otherwise, it will show testingYou are not logged in.
You cannot add a message on login.php and expect it to appear on fakelogin.php auto-magically.
There are a lot of ways to share information between pages and the session variable is one of it.
By using the method below, you can set the session variable id as "Your username or Password is wrong" and since fakelogin.php will print it out if there's a value, this should show the error message.
login.php
<?php
session_start();
//include 'dbh.php';
//probably do not need this can write connection in this file too
$conn = new PDO('mysql:host=localhost;dbname=testtable', 'root', '');
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
if(!$conn){
die("Connection is fubar yo!!! ");
}
$uid = $_REQUEST['uid'];
$pwd = $_REQUEST['pwd'];
$sql = "SELECT * from user WHERE uid='$uid' AND pwd='$pwd'";
$result = $conn->prepare($sql);
$result->execute();
if(!$row = $result->fetch(PDO::FETCH_ASSOC)){
echo("Your username or Password is wrong");
$_SESSION['id'] = "Your username or Password is wrong";
} else {
echo("hey man..it works");
$_SESSION['id'] = $row['id'];
}
header("Location: fakelogin.php");
?>
So when you attempt to login with wrong details, you will see testingYour username or Password is wrong.
For problem with your logout button, there's a problem with your HTML. action attribute should be in the form tag and not the button tag like so.
<form action="logout.php">
<button>LOG OUT</button>
</form>

Related

Login with different role (redirect to different page according to user type )

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.

my login form always access denied

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"
?>

Header function is redirecting to index.php instead of the specified file (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");

Issues while creating a session

I am creating a user session but it's like code has gone wrong somewhere and doesn't hold session, I simply redirect user to a blank page where I echo user id of session holder to check whether it's working or not. Their is no problem with table or db as register page works fine and data gets stored in db. My login.php
<?php
$con = mysqli_connect("localhost","root","","findfriends") or die ("Connection not established");
?>
<?php
if(isset($_POST['login'])){
$username = strip_tags(#$_POST['user_login']);
$password = strip_tags(#$_POST['password_login']);
$result = $con->query("SELECT * FROM users WHERE username='$username' AND password='$password'");
$row = $result->fetch_array(mysqli_both);
session_start();
$_SESSION["userid"] = $row['userid'];
header("Location: test12.php");
}
?>
<h2>Already a member? Login Below</h2>
<form action="" method="POST">
<input type="text" name="user_login" size="25" placeholder="Username"/><br><br>
<input type="password" name="password_login" size="30" placeholder="Passsword"/><br><br>
<input type="submit" name="login" value="Login">
</form>
test.php for checking session
<?php
$con = mysqli_connect("localhost","root","","findfriends") or die ("Connection not established");
?>
<?php
session_start();
?>
<div style="margin-left:30px;margin-right:400px;border:1px solid #000;">
<h2>User id is:</h2>
<?php echo $_SESSION["userid"]; ?>
</div>
Make session_start(); your first line in the file
try by using $_SESSION['userid'] instead of $_SESSION["userid"].

Querying another table after login

This seems like it should be simple, but I've tried it every which way and can't seem to get it to work.
I have this login script which I adapted from an online tutorial. What I'd like to do is have users sign in with a username and password, and if these are correct, have it go after their lab results in another table (same database) and display them. I can get it to sign in, but that's it. Here's the login code:
<?php //Start the Session
session_start();
require('connect.php');
//3. If the form is submitted or not.
//3.1 If the form is submitted
if (isset($_POST['username']) and isset($_POST['password'])){
//3.1.1 Assigning posted values to variables.
$username = $_POST['username'];
$password = $_POST['password'];
//3.1.2 Checking the values are existing in the database or not
$query = "SELECT * FROM `user` WHERE username='$username' and password='$password'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1){
$_SESSION['username'] = $username;
}else{
//3.1.3 If the login credentials doesn't match, he will be shown with an error message.
echo "Invalid Login Credentials.";
}
}
//3.1.4 if the user is logged in Greets the user with message
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Hi " . $username . "! ";
echo "This is the results of your inquiry.<br><br>";
/*This is where I'm assuming the new query needs to go.
Query a different table named "data" and pick out information according to
$username which was put in earlier */
echo "<br><a href='logout.php'>Logout</a>";
}else{
//3.2 When the user visits the page first time, simple login form will be displayed.
?>
<!DOCTYPE html>
<html>
<head>
<title>Lab Sign In Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!-- Form for logging in the users -->
<div class="register-form">
<?php
if(isset($msg) & !empty($msg)){
echo $msg;
}
?>
<h1>Login</h1>
<form action="" method="post">
<p><label>User Name :</label> <input id="username" type="text" name="username" placeholder=
"username"></p>
<p><label>Password   :</label> <input id="password" type="password" name="password"
placeholder="password"></p><a class="btn" href="register.php">Signup</a> <input class=
"btn register" type="submit" name="submit" value="Login">
</form>
</div><?php }
?>
</body>
</html>
A "Join" is what I get when I google it but that doesn't seem right. Could someone help?
You can just use a different query for making it easy:
$sql = mysql_query("SELECT * FROM data WHERE user = '" . mysql_real_escape_string($username) . "'");
Then you can process with this.
Please note that you should not use MySQL driver as it is deprecated, use MySQLi(mproved) instead. And you should escape the POSTed values, this is very important!
Your last else statement is trying to echo the HTML.
You should be using mysqli or PDO since mysql is deprecated.
<?php //Start the Session
session_start();
// require('connect.php');
// Establish connection with database
$con=mysqli_connect("localhost","root","","test");
// Check connection
if (mysqli_connect_errno()){ echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
//3. If the form is submitted or not.
//3.1 If the form is submitted
if (isset($_POST['username']) and isset($_POST['password'])){
//3.1.1 Assigning posted values to variables.
$username = $_POST['username'];
$password = $_POST['password'];
//3.1.2 Checking the values are existing in the database or not
$query = "SELECT * FROM `people` WHERE username='$username' and password='$password'";
$result = mysqli_query($con,$query) or die(mysqli_error());
$count = mysqli_num_rows($result);
//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1){
$_SESSION['username'] = $username;
echo "Valid";
}else{
//3.1.3 If the login credentials doesn't match, he will be shown with an error message.
echo "Invalid Login Credentials.";
}
}
//3.1.4 if the user is logged in Greets the user with message
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Hi " . $username . "! ";
echo "This is the results of your inquiry.<br><br>";
echo "Username: $username";
echo "Session Username:".$_SESSION['username'];
// This is where I'm assuming the new query needs to go.
// Query a different table named "data" and pick out information according to $username which was put in earlier
echo "
Logout";
}else{
//3.2 When the user visits the page first time, simple login form will be displayed.
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Lab Sign In Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!-- Form for logging in the users -->
<div class="register-form">
<?php
if(isset($msg) & !empty($msg)){
echo $msg;
}
?>
<h1>Login</h1>
<form action="test.php" method="post">
<p><label>User Name :</label> <input id="username" type="text" name="username" placeholder=
"username"></p>
<p><label>Password :</label> <input id="password" type="password" name="password"
placeholder="password"></p><a class="btn" href="register.php">Signup</a> <input class=
"btn register" type="submit" name="submit" value="Login">
</form>
</div>
</body>
</html>

Categories