I'm just learning the PHP basics and I need to create a blog. I've followed a few tutorials but I can't seem to be able to get PHP to recognize when I've pressed the login form I created with HTML.
<?php
session_start(); //keep a session open so no need to relogin
if(isset($_POST['submit'])){ //check to see if submit button is pressed
$user = $_POST['username'];
$pwrd = $_POST['pwrd'];
//add database connection
include('./includes/db_connect.php');
if(empty($user) || empty($pwrd)){
echo 'Please ensure both password and username fields are filled.';
}else{
$pwrd = md5($pwrd);
$query = $db->query("SELECT user_id, username FROM user WHERE username='$user' AND password = '$pwrd'"); //grab username and password from table
if($query->num_rows ===1) {
while ($row = $query->fetch_object()) {
$_SESSION['user_id'] = $row->user_id;
}
header('Location : index.php'); //redirt user to index.php
exit();
}else{
echo 'Wrong credentials';
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<div id="container">
<form action="login.php" method="post">
<p>
<label>Username</label><input type="text" name="username" />
</p>
<p>
<label>Password</label><input type="password" name="pwrd" />
</p>
<input type="submit" value="LogIn" />
</form>
</div>
</body>
</html>
When I press log in while both username and password are empty I get nothing instead of 'Please ensure both password and username fields are filled.'
Any help would be appreciated.
You are checking with if(isset($_POST['submit'])){ but there is no field in the form named submit.
Try with, if ($_SERVER['REQUEST_METHOD'] === 'POST') { instead.
Or rename the submit button to submit [or something else but remember to fix the check as well]
$_POST data comes from the 'name="..."' item. Not type="...". Note that simply checking if POST exists is a risky practice since you can have more than 1 form on the page, so I always use explicit checks of the desired form fields to trigger form handlers.
<?php
session_start(); //keep a session open so no need to relogin
if(isset($_POST['username'])){ //check to see if submit button is pressed
$user = $_POST['username'];
$pwrd = $_POST['pwrd'];
//add database connection
include('./includes/db_connect.php');
if(empty($user) || empty($pwrd)){
echo 'Please ensure both password and username fields are filled.';
}else{
$pwrd = md5($pwrd);
$query = $db->query("SELECT user_id, username FROM user WHERE username='$user' AND password = '$pwrd'"); //grab username and password from table
if($query->num_rows ===1) {
while ($row = $query->fetch_object()) {
$_SESSION['user_id'] = $row->user_id;
}
header('Location : index.php'); //redirt user to index.php
exit();
}else{
echo 'Wrong credentials';
}
}
}
?>
Related
I have a database table that holds a users username, password and other information as well as whether theyre and administrator or not. Its currently set to Char where A is for admin and U is for normal user.
I have the following code which checks if a user exists:
<?php
session_start(); // Starting Session
include_once('config.php');
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['user']) || empty($_POST['pass'])) {
$error = "Please complete both fields";
}
else
{
// Define $username and $password
$user=$_POST['user'];
$_SESSION['login_user']=$user;
$pass=md5($_POST['pass']);
// To protect MySQL injection for Security purpose
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysqli_real_escape_string($mysqli, $user);
$pass = mysqli_real_escape_string($mysqli, $pass);
// SQL query to fetch information of registered users and finds user match.
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE Username='$user' AND Password='$pass'");
if(mysqli_num_rows($result) == 1) {
header("Location: home.php");
} else {
$error = "Username or Password is invalid";
}
mysqli_close($mysqli); // Closing mysqlinection
}
}
?>
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/style.css">
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<title>Login</title>
</head>
<body>
<div id = "logReg">
<span href="#" class="button" id="toggle-login">Log in</span>
</div>
<div id="login">
<div id="triangle"></div>
<h1>Log in</h1>
<form action = "" id = "logregform" method = "POST">
<p id = "err"> <?php if(isset($error)) {echo $error;} ?> </p>
<input id = "logtxt" type="text" placeholder="Username" name = "user" required/>
<input type="password" placeholder="Password" name = "pass" required/>
<input type="submit" value="Log in" name = "submit" />
<br>
<br>
<p id ="bklg">Dont have an account? Sign up</p>
</form>
</div>
</html>
How would i check if Account_Type is A and if so direct the user to another page instead of the normal home.php page?
EDIT:
It works fine however the admin wont log in.
Ive given it test username of 456 and a password of 456 when i enter them into the two textboxes nothing happens, the screen just refreshes and im back on the login page:
new code below:
<?php
session_start(); // Starting Session
include_once('config.php');
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['user']) || empty($_POST['pass'])) {
$error = "Please complete both fields";
}
else
{
// Define $username and $password
$user=$_POST['user'];
$pass=md5($_POST['pass']);
// To protect MySQL injection for Security purpose
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysqli_real_escape_string($mysqli, $user);
$pass = mysqli_real_escape_string($mysqli, $pass);
// SQL query to fetch information of registered users and finds user match.
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE Username='$user' AND Password='$pass'");
if ($row = mysqli_fetch_array($result)) {
//set the session variables
$_SESSION['Username'] = $row['Username'];
$_SESSION['Account_Type'] = $row['Account_Type'];
if ($row['Account_Type'] === 'A') {
header ("location: adminHome.php");
exit;
} else {
header ("location: home.php");
exit;
}
} else {
$error = "Username or Password is invalid";
}
mysqli_close($mysqli); // Closing mysqlinection
}
}
?>
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/style.css">
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<title>Login</title>
</head>
<body>
<div id = "logReg">
<span href="#" class="button" id="toggle-login">Log in</span>
</div>
<div id="login">
<div id="triangle"></div>
<h1>Log in</h1>
<form action = "" id = "logregform" method = "POST">
<p id = "err"> <?php if(isset($error)) {echo $error;} ?> </p>
<input id = "logtxt" type="text" placeholder="Username" name = "user" required/>
<input type="password" placeholder="Password" name = "pass" required/>
<input type="submit" value="Log in" name = "submit" />
<br>
<br>
<p id ="bklg">Dont have an account? Sign up</p>
</form>
</div>
<script>
$('#toggle-login').click(function(){
$('#login').slideToggle('fast');
});
</script>
</html>
You are going about this the wrong way. Every page that requires the user to be authenticated should check at the very start if the user is authenticated and at what level. The way to do that is to use the session.
Right now you are setting the session variable before you even check whether the user / password combination is correct so you are effectively logging in anybody who enters a username.
You need to store the variables in the session only upon successful login and as mentioned you need to get a row from your result set to get the user information:
// Personally I would use a prepared statement here
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE Username='$user' AND Password='$pass'");
if ($row = mysqli_fetch_array($result)) {
// Now you can set the session variables
$_SESSION['Username'] = $row['Username'];
$_SESSION['Account_Type'] = $row['Account_Type'];
// Add any additional user information to the session that you might need later on
if ($row['Account_Type'] === 'A') {
header ("location: adminHome.php");
exit;
} else {
header ("location: home.php");
exit;
}
} else {
$error = "Username or Password is invalid";
}
Now in every page where a user is required you can do:
session_start();
if (isset($_SESSION['Username']))
{
// valid user, additional checks for user type?
}
else
{
// not a valid / logged in user
}
Note:
(unsalted...) md5 is unsafe to use for passwords, see Secure hash and salt for PHP passwords;
$row = mysqli_fetch_array($result);
if ($row['Account_Type'] === 'A') {
} elseif ($row['Account_Type'] === 'U') {
} else {
}
I am designing a website which have four modules Admin, branch admin, reporter, accountant where each of the respective person can login to their respective page like admin will login to the admin page and reporter will login to it's page, but the code is not working.
When I try login to any module it login only to the admin page and does goes to the branch admin or reporter or accountant.
This is my index.php page
<?php
include('login.php'); // Includes Login Script
if(isset($_SESSION['login_user']))
{
header("Location: admin.php");
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>LoginIN</title>
<link href="styles/bootstrap.min.css" rel="stylesheet">
<link href="styles/signin.css" rel="stylesheet">
</head>
<body>
<div id="wrapper">
<header id="top">
<center><h1>Reporter Management System</h1></center>
<div class="container">
<form class="form-signin" role="form" action ="" method="post">
<h2 class="form-signin-heading">Please sign in</h2>
<input type="email" name="username" class="form-control" placeholder="Email address" required autofocus>
<input type="password" name="password" class="form-control" placeholder="Password" required>
<br>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me">Remember me
<br>
</label>
</div>
<input name="submit"button class="btn btn-lg btn-primary btn-block" type="submit" value=" Sign in">
<span><?php echo $error; ?></span>
<br>
Forgot your password?
</body>
</html>
This is my login.php page
<?php
error_reporting( E_ALL );
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$usr=$_POST['username'];
$pwd=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$con = mysql_connect("localhost", "root1", "oec#123") or die('Error Connecting to mysql server');
// To protect MySQL injection for Security purpose
$username = stripslashes($usr);
$password = stripslashes($pwd);
$username = mysql_real_escape_string($usr);
$password = mysql_real_escape_string($pwd);
// Selecting Database
$db=mysql_select_db('rms',$con);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select username, password from login where password='$pwd' AND username='$usr'", $con) or die('Error querying database');
$rows = mysql_num_rows($query);
while ($rows = mysql_fetch_array($query)) {
$_SESSION['Sl_no']=$rows['Sl_no'];
if ($rows ==1)
{
// Initializing Session
header("location: admin.php"); // Redirecting To Other Page
}
elseif ($rows==2)
{
header("location: branchadmin.php");
}
elseif($rows==3)
{
header("location: accountant.php");
}
elseif($rows==4)
{
header("location: reporter.php");
}
else
{
$error = "Username or Password is invalid";
}
}
mysql_close($con); // Closing Connection
}
}
?>
I think the problem is with your retrieval and condition statements around this area
while ($rows = mysql_fetch_array($query)) {
$_SESSION['Sl_no']=$rows['Sl_no'];
if ($rows ==1)
{
and since the login page is redirecting to the admin.php every time, this could be because you put the number of returned rows in the $rows variable like $rows = mysql_num_rows($query); and if it is returning one row this would meet the the if ($rows ==1){header("location: admin.php");} condition you check later on...
Just an educated (and/or non-educated) guess.
Why don't you put a column in your db that indicates the users level of access. Like user_level or something where admin = 1, branchadmin = 2, accountant = 3, etc. and then do a check and re-direct based on that.
So when you check whether the username and password from the form are in the the database and if it is then you could look at their user level to see where to re-direct them.
if ($rows === 1){
$row_array = mysql_fetch_assoc($query);
if ($row_array['admin_level'] == 1){
header("location: admin.php"); // Redirecting To Other Page
}
elseif ($row_array['admin_level']==2){
header("location: branchadmin.php");
}
elseif($row_array['admin_level']==3){
header("location: accountant.php");
}
elseif($row_array['admin_level']==4){
header("location: reporter.php");
}
else{
$error = "Username or Password is invalid";
}
}
mysql_close($con); // Closing Connection
Does that make sense or am I misunderstanding what you want to achieve?
In this case, you have to use multiple session variables like $_SESSION['email'] and $_SESSION['type'].
Here, $email will be the username of particular user and $type will be the type of user like admin, branch admin, reporter, accountant etc.
These two session variables needs to be set while user is logging in.
For example, consider the following code snippet:
if(isset($_SESSION['email']))
{
if($_SESSION['type'] == "admin")
{
header('location:admin.php');
}
else if($_SESSION['type'] == "reporter")
{
header('location:reporter.php');
}
}
Im creating a website where users can login to buy books and collect them from store. I have a login screen where both normal users as well as staff use to login. However im trying to find a way to differentiate between normal users and staff.
I have a table called "users" where one of the columns is called "account_type" which can hold a value of U for normal user and A for admin.
this is the code i currently have:
<?php
session_start(); // Starting Session
include_once('config.php');
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['user']) || empty($_POST['pass'])) {
$error = "Please complete both fields";
}
else
{
// Define $username and $password
$user=$_POST['user'];
$_SESSION['login_user']=$user;
$pass=md5($_POST['pass']);
// To protect MySQL injection for Security purpose
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysqli_real_escape_string($mysqli, $user);
$pass = mysqli_real_escape_string($mysqli, $pass);
// SQL query to fetch information of registered users and finds user match.
$query = mysqli_query($mysqli, "SELECT * FROM users where Username='$user' AND Password='$pass'");
$rows = mysqli_num_rows($query);
if ($rows == 1) {
header("location: home.php"); // Redirecting To Other Page
}elseif ($rows["account_type"] == "A"){
header ("location: adminHome.php");
}else {
$error = "Username or Password is invalid";
}
mysqli_close($mysqli); // Closing mysqlinection
}
}
?>
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/style.css">
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<title>Login</title>
</head>
<body>
<div id = "logReg">
<span href="#" class="button" id="toggle-login">Log in</span>
</div>
<div id="login">
<div id="triangle"></div>
<h1>Log in</h1>
<form action = "" id = "logregform" method = "POST">
<p id = "err"> <?php if(isset($error)) {echo $error;} ?> </p>
<input id = "logtxt" type="text" placeholder="Username" name = "user" required/>
<input type="password" placeholder="Password" name = "pass" required/>
<input type="submit" value="Log in" name = "submit" />
<br>
<br>
<p id ="bklg">Dont have an account? Sign up</p>
</form>
</div>
<script>
$('#toggle-login').click(function(){
$('#login').slideToggle('fast');
});
</script>
</html>
Line 24-30 is where ive put the check but it doesnt seem to work.
I dont get any errors it just skips to the validation part when i try the admins login details and says "username or password is invalid" It does login as the normal user however.
Any ideas?
$rows = mysqli_num_rows($query);
if ($rows == 1) {
header("location: home.php"); // Redirecting To Other Page
}elseif ($rows["account_type"] == "A"){
...
}
Take a closer look at this. You are setting $rows with mysqli_num_rows, it will not be an array and should only be an integer. You need to use a fetch function to get the column data. The fetch would be run using the MySQLi statement variable (in your case the return value of mysqli_query or $query. Read more about fetch here: http://php.net/manual/en/mysqli-stmt.fetch.php
P.S. Your code a little messy. You use stripslashes then real escape, why not use prepared statements? They are safer and more efficient because they let the DBMS (MySQL) handle the variables. Read more about prepared statements here: http://php.net/manual/en/mysqli.prepare.php
When a person logs in , the online column in the table is set to 1 , and when he logs out , it is set to 0 . I achieved the Login script , but problems on ending the session with SQL query .. Please do help !
There is No Error Displayed but Online value remains as 1 even after logging out
**LOGOUT SCRIPT**
<?php
$offline = $_SESSION["username"] ;
?>
<?php
//If the user is logged, we log him out
if(isset($offline))
{
//We log him out by deleting the username and userid sessions
unset($_SESSION['username'], $_SESSION['userid']);
$con=mysqli_connect("localhost","root","","chat");
mysqli_query($con,"UPDATE users SET Online=0
WHERE username='.$offline.'");
mysqli_close($con);
?>
LOGIN SCRIPT
<?php
$ousername = '';
//We check if the form has been sent
if(isset($_POST['username'], $_POST['password']))
{
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$ousername = stripslashes($_POST['username']);
$username = mysql_real_escape_string(stripslashes($_POST['username']));
$password = stripslashes($_POST['password']);
}
else
{
$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
}
//We get the password of the user
$req = mysql_query('select password,id from users where username="'.$username.'"');
$dn = mysql_fetch_array($req);
//We compare the submited password and the real one, and we check if the user exists
if($dn['password']==$password and mysql_num_rows($req)>0)
{
//If the password is good, we dont show the form
$form = false;
//We save the user name in the session username and the user Id in the session userid
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
$con=mysqli_connect("localhost","root","","chat");
$sql = mysql_query('UPDATE users SET Online=1 where username="'.$username.'"');
?>
<div class="message">You have successfuly been logged. You can access to your member area.<br />
Home</div>
<?php
}
else
{
//Otherwise, we say the password is incorrect.
$form = true;
$message = 'The username or password is incorrect.';
}
}
else
{
$form = true;
}
if($form)
{
//We display a message if necessary
if(isset($message))
{
echo '<div class="message">'.$message.'</div>';
}
//We display the form
?>
<div class="content">
<form action="connexion.php" method="post">
Please type your IDs to log in:<br />
<div class="center">
<label for="username">Username</label><input type="text" name="username" id="username" value="<?php echo htmlentities($ousername, ENT_QUOTES, 'UTF-8'); ?>" /><br />
<label for="password">Password</label><input type="password" name="password" id="password" /><br />
<input type="submit" value="Log in" />
</div>
</form>
</div>
And , when I do the SQL query , How do I do the if Online = 1 , display online.png ? else 'Blank space ' ?
Thanks in advance !
The below code is for logout.php
<?php
//If the user is logged, we log him out
if(isset($_SESSION['username']))
{echo $_SESSION['username'];
//We log him out by deleting the username and userid sessions
$username=$_SESSION['username'];
$sql="UPDATE users SET online=0 WHERE username='$username'";
mysql_query($sql);
unset($_SESSION['username'], $_SESSION['userid']);
?>
And this one for sign_up.php
if(isset($_POST['username'], $_POST['password'], $_POST['passverif'], $_POST['email'], $_POST['username']))
use session_start();
ANd session_destroy(); FOR LOGOUT.
i'm creating a php login page. i can't get the page to redirect (to index.php in this case) when the $_SESSION variable "success" is passed. I can get the success message to work so I think my form and query are fine. What am I missing here?
Here's the form (login.php):
<? $page = "login-page";//body tag class
$title = "Log in to your Bloggr Account";//title tag text
session_start();
require_once('includes/header.php');
print_r($_SESSION); ?>
<p class="errors" id="errors">
<? if(!empty($_SESSION['errors'])){ ?>
<script type="text/javascript"> $(function() {
setTimeout(function(){
$("#errors").fadeIn(500);}, 500)});
<script>
<? foreach($_SESSION['errors'] as $error){
echo $error;}
session_unset($_SESSION['errors']);
} ?>
</p> <? if(!empty($_SESSION['success'])){
header("Location: index.php");
echo $success;
session_unset($_SESSION['success']); } ?>
<form action="login-post2.php" method="post" class="admin-form login">
<label for="userName">User Name <label>
<input type="text" name="userName" class="user-name" value="" />
<label for="password">Password</label>
<input type="password" name="password" class="password" />
<input type="submit" class="submit" name="register-submit" value="Log In!" />
</form>
Here is the post file (login-post2.php)
<? if($_SERVER["REQUEST_METHOD"] == "POST"){
session_start();
require_once('../_db_connect.php');
$errors = array();
$success = "You're logged in!";
if(empty($_POST['userName'])){
$errors[] = "Please enter a user name.";
}else[
$userName = $_POST["userName"];
}
if(empty($errors)){
$query = "SELECT userName, password FROM users WHERE userName = '$userName' and password = SHA1('$password')";
$result = mysqli_query($dbconnect, $query);
if(!result){
$errors[] = "Please try again!";
} else{
$success;
}
}
$_SESSION['errors'] = $errors;
$_SESSION['success'] = $success;
exit();
} ?>
Sorry if some of the formatting is a bit off.
*EDIT [SOLVED]
for anyone who comes across this in the future here's what i did. here's where the biggest part of my problem was:
if(empty($errors)){
$query = "SELECT userName, password FROM users WHERE userName = '$userName' and password = SHA1('$password')";
$result = mysqli_query($dbconnect, $query);
if(mysqli_num_rows($result) == 1){//if username and password match;
$row = mysqli_fetch_array($result);
$_SESSION['loggedIn'] = $loggedIn;
header("Location: index.php");
exit();
}
} else{
$_SESSION['errors'] = $errors;
header("Location: login.php");
exit();
}
I didn't do a good job of formatting my if/else statement for $errors. Part of my problem, which I knew at the time but couldn't figure out, was that I needed a way to send headers twice. one way if i had $errors and another way if i didn't. the way i had before was trying to send it twice without a conditional. my solution was to wrap the last bit of my statement as the else which allowed me to send the user back to the login page if there were errors and over to the index page if they were successfully logged in. That's it. Hope this helps others in the future.
You need to call header() before you send any other content (either through some PHP thing like echo or var_dump() or just HTML between PHP tags).
You're sending out:
<p class="errors" id="errors">
<script type="text/javascript"> $(function() {
setTimeout(function(){
$("#errors").fadeIn(500);}, 500)});
<script>
echo $error;}
</p>
before you send the headers. Refactor your code to move the call to header() before these.
header("Location: login.php);
Missing a quote could be a problem.