If(..){include}, includes anyways - php

I am trying to make a simple Login system for admins. Nothing too special, since it's my first one. I am trying to verify if the username and password inputted are the same as the one in the database, and then include the rest of the page. No errors, everything works as it should, the database access is good, but it's like the if statement isn't there. It just includes the rest of the page on load.
<form action="admin.php" method="POST" class="login">
<input type="text" placeholder="Password" name="username" required>
<input type="password" placeholder="Password" name="password" required>
<input type="submit" value="Log In">
</form>
<?php
require('connect.php');
$admin = <<<SQL
SELECT *
FROM admins
SQL;
$username = $_POST['username'];
$pw = $_POST['password'];
$result = $db->query($admin);
while($row = $result->fetch_assoc()){
if($username == $row['username'] && $pw == $row['password']){
include('admininclude.php');
} else {
echo 'You are not cool enought to enter. (Username or Password wrong.)';
}
}
$db->close();
?>
Thanks in advance!

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.

How to do the next step for login

I am learning MySQL and PHP and I trying to build a simple login webpage and connect with MySQL.
I have built the page with HTML and CSS, also I downloaded PHP and installed MySQL, I am getting confused about how to combine those things and when I input my password and username it will go to successful page.
I am not seeking an answer but need some suggestions for the next step.
PLEASE NOTE - the way my SQL queries are written here are open to SQL injection (see here to get the changes you would need to make)
So to start. You want to create a database table to store your users, a form to create users, and some code to query the data into the database.
i would start with a form like this:
<form method="post" class="mt-3">
<input type="hidden" name="do" value="create" />
<div class="form-group">
<label for="itemName">First Name</label>
<input type="text" class="form-control" name="firstName">
</div>
<div class="form-group">
<label for="serialNumber">Last Name</label>
<input type="text" class="form-control" name="lastName">
</div>
<div class="form-group">
<label for="serialNumber">Username</label>
<input type="text" class="form-control" name="userName">
</div>
<div class="form-group">
<label for="serialNumber">Password</label>
<input type="password" class="form-control" name="passWord">
</div>
<a id="create-member" class="btn btn-success text-white">Submit</a>
</form>
then you want some code that will take the values you have in that form and turn them into a query to add that info into your table.
if(isset($_POST['do'])) && $_POST['do'] == 'create'
{
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$username = $_POST['userName'];
$password = password_hash($_POST['passWord'], PASSWORD_BCRYPT);
$sql = "INSERT INTO members (first_name, last_name, username, password) VALUES ('".$firstName."', '".$lastName."', '".$username."', '".$password."')";
mysqli_query($conn, $sql); //$conn is set in my header file and included into every page.
}
That is pretty much the process for creating a user and adding it to your table, obviously you'll have to break it down and change values to what you have in your table etc.
Next it's the case of verifying a login.
first, a login form:
<form method="post">
<input type="hidden" name="do" value="login" />
<div class="form-group">
<label for="usename">Username</label>
<input type="text" class="form-control" id="username" name="username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
and then an authentication query to follow, this will take the info in the login page, hash the password you entered and then compare it with the one in your database.
if (isset($_POST['do']) && $_POST['do'] == 'login')
{
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT id, first_name, last_name, password FROM members WHERE username= '$username'";
$query = mysqli_query($conn, $sql) or die(mysqli_error($conn));
if($query->num_rows == 0)
{
echo "Username or password incorrect";
}else{
$data = mysqli_fetch_array($query);
if(!password_verify($password, $data['password']))
{
echo "Username or password incorrect";
}else{
session_regenerate_id();
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $_POST['username'];
$_SESSION['member_id'] = $data['id'];
$_SESSION['first_name'] = $data['first_name'];
$_SESSION['last_name'] = $data['last_name'];
}
}
}
}
?>
don't be scared about the $_SESSION variables at the bottom, i just set all user data as that so it's easier to access it on other pages, then i just follow with a header to my index.php page. In my header i also check to see that $_SESSION['loggedin'] is set to true and if not it redirects them to the login page (also be care to take into account the user might be on the login page, you dont want a redirect error)
This is my first detailed answer on this site so i hope it helps you :)

Is anything wrong with this code?

I used this code to create a user registration page in my website. I firstly connected to my database and then did the below codes ----->
<form action="index.php" method="post">
<p id="usr1">Name : </p><input id="input1" placeholder="Username" type="text" name="username" required> </br>
</br>
<p id="usr2">Password : </p><input id="input2" placeholder="Password" type="text" name="pwd" required> </br>
<p id="usr3">Password : </p><input id="input3" placeholder="Re-Type your password" type="text" name="cpwd" required> </br>
</br>
<input id="sub" name="subbox" type="submit">
</form>
<?php
if (isset($_POST['submit_button'])) {
$username= $_POST['username'];
$password=$_POST['pwd'];
$conpwd=$_POST['cpwd'];
}
if ($password == $conpwd) {
$query = "SELECT * FROM login WHERE name='$username' ";
$query_run = mysqli_query($con,$query);
if (mysqli_num_rows($query_run) > 1) {
echo '<script type="text/javascript">alert("This Username Already exists. Please try another username!")</script>';
// the above code will check if the username is already taken or not.
}else {
$query = "insert into login values('$username' , '$password')";
$query_run = mysqli_query($con,$query);
if ($query_run) {
echo '<script type="text/javascript">alert("Registration Successful!")</script>Click Here To Continue';
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header( "Location: homepage.php");
}else {
echo '<script type="text/javascript">alert("Server Error. Please try again after a few minutes!")</script>';
}
}
}else {
echo "Please check and re-type both passwords";
}
?>
But it always return some errors.This is what I see when i try to run the code
Is anything wrong with this code?
To answer your initial question, yes there is something wrong. Your code is vulnerable to SQL injection. You should have a look at: How can I prevent SQL injection in PHP? And password is stored plain in your database, which means no respect for your user. There are some other problems with code style but it's just bonus.
Anyway, the thing that cause you the "alert" problem is that submit_button button does not exists. There is no button with that name. Your if condition is always false. So you have to replace:
if (isset($_POST['submit_button'])) {
With
if (isset($_POST['subbox'])) {
And maybe add a value to your input (not sure it's required, I did not tested):
<input id="sub" name="subbox" type="submit" value="1">
Thanks to #Fred-ii-

Login script cannot successfully check user password

I have my Oral defense at school next week.. and I tried searching for answers.. none was working so I figured out to ask here right away..
So okay.. my page is here and I connected my php page to my database (godaddy) and its working.. in registration.php, you can add employee and its being added to my database "table" but when I try login.php it said.. "Incorrect password" but the password is correct in my database..
its like.. my php can be connected to database
but my database doesn't want to connect to my php page..
what's wrong with my code? Can you help me? please?
<?php
require('db.php');
session_start();
if (isset($_POST['username'])){
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$username = mysql_real_escape_string($username);
$password = stripslashes($password);
$password = mysql_real_escape_string($password);
$query = "SELECT * FROM 'users' WHERE username='$username' and password='".md5($password)."'";
$result = mysql_query($query) or die(mysql_error());
$rows = mysql_num_rows($result);
if($rows==1){
$_SESSION['username'] = $username;
header("Location: home.php");
} else {
echo "<div class='form'><h3>Username/password is incorrect.</h3><br/><div>";
}
}else{
?>
<div class="form">
<h1>Log In</h1>
<form action="" method="post" name="login">
<input type="text" name="username" placeholder="Username" required />
<input type="password" name="password" placeholder="Password" required />
<input name="submit" type="submit" value="Login" />
</form>
</div>
<?php } ?>

PHP and MySQL Cookie and Header doesn't work

I have a problem and I hope someone will be able to find a solution.
I just changed hoster and the website doesn't work completely.
Basically the problem is that some code doesn't work.
Where it checks if(!empty($db_password) and ($md5pass == $db_password))
The echo works but the other things don't and it's not only there. I have a similar problem with other files as well.
$username = $_POST['user'];
if(isset($username))
{
$password = $_POST['password'];
$md5pass = md5($password);
$check_user = "SELECT ID,username,password FROM Members ";
$check_user .= "WHERE username = '".$username."'";
$checkuser_query = mysqli_query($dbconnection,$check_user);
while($row = mysqli_fetch_array($checkuser_query,MYSQL_ASSOC))
{
$db_userid = $row['ID'];
$db_username = $row['username'];
$db_password = $row['password'];
$db_avatar = $row['avatar'];
}
if(!empty($db_password) and ($md5pass == $db_password))
{
echo 'you are not awesome.';
setcookie("LoginAuthorised","LoginAuthorised",time()+7200,"/");
setcookie("id",$db_userid,time()+7200,"/");
setcookie("username",$db_username,time()+7200,"/");
header("Location: user.php?value=confirm");
}else
{
echo '<div id="error">Password does not match</div>';
}
}
echo '<p></p><p></p>
<div id="lg_login_form">
<form name="login_form" method="post">
<div id="lg_login_title">Log In</div>
<div id="lg_login_form2">
<label>Username:</label>
<input type="text" name="user" id="username" value="" maxlength="20" />
<label>Password:</label>
<input type="password" name="password" value="" maxlength="20" />
<input name="submit_login" type="submit" value="Log In" id="lg_submit_log" />
<p></p>
<p></p>
<div id="lg_control_text">You have to login to access User Panel</div>
</div>
</form>
<form name="register_redirect" action="user.php?value=register" method="post" id="lg_register_redirect" >
<label>If you want to login you have to register first. Registering takes only a few moments and it gives you multiple features.<br/></label>
<input name="submit_registration" type="submit" value="Register" id="lg_submit_reg_log" />
<p></p>
</form>
</div>';
You're sending headers before setcookie() is called, which is probably why you're having issues. Remove the line that says echo 'you are not awesome.';

Categories