Basically what would I need to add to this code in the login.php to match the hash created in the register.php:
login.php
if (isset($_POST['Login'])) {
$username = $_POST['email'];
$store_password = $_POST['pword'];
check($username, $store_password);
}
function check($username, $pword){
$conn = mysqli_connect('localhost', 'root', 'root', 'Registrar');
$check = "SELECT * FROM Users WHERE email='$username'";
$check_q = mysqli_query($conn, $check) or die("<div class='loginmsg'>Error on checking Username<div>");
if (mysqli_num_rows($check_q) == 1) {
login($username, $pword);
}
else{
echo "<div id='loginmsg'>Wrong Email or Password</div>";
}
}
function login($username, $pword){
$conn = mysqli_connect('localhost', 'root', 'root', 'Registrar');
$login = "SELECT * FROM Users WHERE email='$username' and pword='$pword'";
$login_q = mysqli_query($conn, $login) or die('Error on checking Username and Password');
if (mysqli_num_rows($login_q) == 1){
header('Location: account.php');
echo"<div id='loginmsg'> Logged in as $username </div>";
$_SESSION['username'] = $username;
}
else {
echo "<div id='loginmsg'>Wrong Password </div>";
}
}
to match the password hash in the register.php
register.php:
$uname = $_POST['uname'];
$email = $_POST['email'];
$pword = $_POST['pword'];
$store_password = password_hash('pword', PASSWORD_BCRYPT, array('cost' => 10));
Any assistance would be appreciated.
You have to use function password_verify like this
if (password_verify($given_password, $stored_password)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
So you have to retrieve the results from db for the given username and compare the password.
In fact
function login($username, $pword){
$conn = mysqli_connect('localhost', 'root', 'root', 'Registrar');
$login = "SELECT email, pword FROM Users WHERE email='$username'";
$login_q = mysqli_query($conn, $login) or die('Error on checking Username and Password');
if (mysqli_num_rows($login_q) == 1){
if(password_verify($pword, mysqli_fetch_field($login_q,1))){
header('Location: account.php');
echo"<div id='loginmsg'> Logged in as $username </div>";
$_SESSION['username'] = $username;
}
else {
echo "<div id='loginmsg'>Wrong Password </div>";
}
}
else {
echo "<div id='loginmsg'>Unknown Username </div>";
}
}
You should separate tasks, you will want to have maybe 2-4 or so functions (or methods via a class). Here is a really simple example of the workflow. I am going to use PDO because I know it better:
// This is just simple but you can make this as elaborate as you want, but
// if you always use the same function to connect, you will will find troubleshooting
// that much easier.
function connection()
{
return new PDO('mysql:host=localhost;dbname=Registrar','root','root');
}
// You want to make a simple validation function where that's all it does,
// you don't want to put a bunch of html in here because you can reuse this function
// elsewhere in other scripts if need be.
function validate($email,$password,$con)
{
// Just look up by email only
$sql = "SELECT * FROM `Users` WHERE `email`= ?";
$query = $con->prepare($sql);
$query->execute(array($email));
$result = $query->fetch(PDO::FETCH_ASSOC);
// If you don't get a row, just return false (didn't validate)
if(empty($result['email']))
return false;
// $result['password'] should have been stored as a hash using password_hash()
return password_verify($password,$result['password']);
}
// Do a quick updater to make it easier on yourself.
// You don't use this in this script but it gives you an idea about what to
// do when you are saving passwords via password_hash()
function updatePassword($email,$password,$con)
{
$hash = password_hash($password, PASSWORD_DEFAULT);
$sql = 'UPDATE `Users` set `password` = ? where `email` = ?';
$query = $con->prepare($sql);
$query->execute(array($hash,$email));
}
session_start();
$con = connection();
// Check there is a post and that post is valid email address
// At this point you can add more messaging for errors...
if(!empty($_POST['email']) && filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) {
// Run our validation function
$valid = validate($_POST['email'],$_POST['password'],$con);
if($valid) {
$_SESSION['username'] = $_POST['email'];
header('Location: account.php');
exit;
}
else {
die("<div id='loginmsg'>Wrong Password</div>");
}
}
Related
I have a problem in my php code. I want to make login system which takes username and password from database. I almost made everything work. But there is one problem.. When you enter name and password/ doesn't matter what, even random/ it logs me in and redirects me to the place i want. How to fix that and make it use only right username and password from database ? I will import my login code file here. Thanks in advance, sorry for my English.
<?php
include 'dbh.php';
$uid = $_POST['uid'];
$pwd = $_POST['uid'];
$query = "SELECT * FROM user WHERE uid='$uid' AND pwd='$pwd'";
$result = mysqli_query($conn, $query);
if ($result = mysqli_query($conn, $query))
{
while ($row = mysqli_fetch_assoc($result))
{
printf("Login success\n");
}
// If the while loop fails, password/username combo was incorrect
printf("Login failed - Invalid username or password.");
} else {
printf("Login failed, could not query the database.\n");
}
header("Location: panel.php");
?>
First of all, you are WIDE OPEN to SQL Injection, you will want to update that. Its covered in tons of other places, look it up.
But to fix your issue, You are redirecting regardless of your checks. Move this to your while loop:
while ($row = mysqli_fetch_assoc($result))
{
printf("Login success\n");
header("Location: panel.php");
}
Having that at the bottom means it gets fired no matter what.
Use mysqli_num_rows
$sql="SELECT * FROM user WHERE uid='$uid' AND pwd='$pwd'";
if ($result=mysqli_query($con,$sql))
{
if (mysqli_num_rows($result)!=0) {
printf("Login success\n");
}else{
printf("Login failed - Invalid username or password.");
}
mysqli_free_result($result);
}
Try this
<?php
function Db(){
$host = "localhost"; // your db settings
$username = "yourusername";
$password = "yourpass";
$db = "users";
$conn = new mysqli($host, $username, $password, $db);
// use mysqli instead mysql_connect, it is outdated I guess
if(!$conn){
die("Could not connect");
}
}
if(isset($_POST['login'])){
$uid = trim($_POST['username']);
$pwd = trim($_POST['password']);
if($uid == ""){
$err[] = "Username is missing.";
}elseif($pwd == ""){
$err[] = "Password is missing.";
}else{ // When validation succeed then make query.
$db = Db();
$uid = $db->real_escape_string($uid); // escape strings from mysql injection
$pwd = $db->real_escape_string($pwd);
$sql = "SELECT * FROM users
WHERE username = '$uid'
AND password = '$pwd'";
$result = $db->query($sql);
if($result->num_rows == 1){
header("location:panel.php"); // login succeed
}else{
$err[] = "Username or password are incorrect";
header("location:login.php"); // login failed
}
}
}
?>
<?php
if(isset($err)):
foreach($err as $loginErr):
echo $loginErr; // Print login errors.
endforeach;
endif;
?>
<!-- HTML login form goes here -->
I have realized why i can't actually access userdata (after i am logged) old way to find the username is $_SESSION['username']; (assuming there is a row as 'username' in MySQL database)
So as i have a test account as "good25" (reason to choose numbers was to see if Alphanumeric inputs works fine.. its just checkup by me.. nevermind)
Problem :
assuming, i have rows in a table as 'username' and all of his information.. such as 'password', 'email', 'joindate', 'type' ...
On net i found out how to snatch out username from Session
<?php session_start(); $_SESSION('username'); ?>
successful!!
i had an idea to check if session is actually registering or no??
after a log on start.php i used this code
if(isset($_SESSION['username'])) { print_r($_SESSION['username']); }
the result was "1" (while i logged in using this username "good25")
any suggestions?
index.php (lets say, index.php just holds registration + Login form + registration script.. in login form, action='condb.php')
<?php
require 'condb.php';
if (isset($_POST['btn-signup']))
{
//FetchInputs
$usern = mysqli_real_escape_string($connection,$_POST['username']);
$email = mysqli_real_escape_string($connection,$_POST['email']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$repassword = mysqli_real_escape_string($connection,$_POST['repassword']);
$usern = trim($usern);
$email = trim($email);
$password = trim($password);
$repassword = trim($repassword);
//SearchUser
$searchusr = "SELECT username FROM $user_table WHERE username='$usern'";
$usersearched = mysqli_query($connection, $searchusr);
$countuser = mysqli_num_rows($usersearched);
//SearchEmail
$searcheml = "SELECT email FROM $user_table WHERE email='$email'";
$emlsearched = mysqli_query($connection, $searcheml);
$counteml = mysqli_num_rows($emlsearched);
//RegisteringUser
if ($countuser == 0)
{
if ($counteml == 0)
{
$ctime = time();
$cday = date("Y-m-d",$ctime);
$aCode = uniqid();
$adduser = "INSERT INTO $user_table(username, email, password, realname, activationcode, verified, joindate, type, points) VALUES ('$usern','$email','$password','$name','$aCode','n','$cday','Free',$signPoints)";
if (mysqli_query($connection, $adduser))
{
?><script>alert('You have been registered');</script><?php
}
else {
?><script>alert('Couldnt Register, please contact Admin<br><?mysqli_error($connection);?>');</script><?php
}
} else {
?><script>alert('Email already exists!');</script><?php
}
} else {
?><script>alert('Username already exists!');</script><?php
}
}
?>
condb.php
$connection = mysqli_connect($db_server, $db_user, $db_pass);
mysqli_select_db($connection, $db_name);
if(!$connection) {
die ("Connection Failed: " . mysqli_connect_error);
}
if (isset($_POST['btn-login']))
{
$uname = mysqli_real_escape_string($connection,$_POST['uname']);
$upass = mysqli_real_escape_string($connection,$_POST['upass']);
//FindUser
$finduser = "SELECT * FROM $user_table WHERE username='$uname' AND password='$upass'";
$findinguser = mysqli_query($connection,$finduser);
$founduser = mysqli_num_rows($findinguser);
//ConfirmPassword
if ($founduser > 0)
{
session_start();
$_SESSION['username'] = $username;
$_SESSION['username'] = true;
if ($findinguser != false)
{
while ($fetchD = mysqli_fetch_array($findinguser, MYSQLI_ASSOC))
{
$fetchD['username'] = $usernn;
$fetchD['email'] = $email;
$fetchD['userid'] = $uid;
$fetchD['realname'] = $rlnm;
$fetchD['points'] = $pts;
$fetchD['type'] = $membertype ;
}
header("Location: start.php");
} else {
echo mysqli_error();
}
} else {
header("Location: index.php");
?><script>alert('Wrong details, please fill in correct password and email');</script><?php
}
}
I am not asking you to build a script.. just little help please? (Thank you so so so so so much, as i am a self-learner, you don't have to say everything.. just a clue is enough for me)
may be you can try this code
<?php
require_once 'require.inc.php';
//session_start();
if (isset($_POST['btn-login']))
{
$uname = mysqli_real_escape_string($_POST['uname']);
$upass = mysqli_real_escape_string($_POST['upass']);
$search = mysqli_query($connection, "SELECT username, userid, password from $user_table WHERE username='$uname' AND password='$upass'");
$match = mysqli_fetch_assoc($search);
if ($match == 1 and $match['password'] == md5($upass))
{
$_SESSION['username'] = $match['userid'];
} else {
?>
<script>alert('Password or E-mail is wrong. If you havent registered, Please Register');</script>
<?php
}
}
if (isset($_SESSION['username']) or isset($match['userid'])){
header("Location:start.php");
}
if (isset($_POST['btn-signup']))
{
$name = mysqli_real_escape_string($_POST['name']);
$usern = mysqli_real_escape_string($_POST['username']);
$email = mysqli_real_escape_string($_POST['email']);
$password = mysqli_real_escape_string($_POST['password']);
$repassword = mysqli_real_escape_string($_POST['repassword']);
$name = trim($name);
$usern = trim($usern);
$email = trim($email);
$password = trim($password);
$repassword = trim($repassword);
$query = "SELECT email FROM $user_table WHERE email='$email'";
$result = mysqli_query($connection, $query);
$count = mysqli_num_rows($result);
$querytwo = "SELECT username FROM $user_table WHERE username='$usern'";
$resulttwo = mysqli_query($connection, $querytwo);
$counttwo = mysqli_num_rows($resulttwo);
if ($count == 0 AND $counttwo == 0)
{
if ($password == $repassword) {
if (mysqli_query($connection, "INSERT INTO $user_table(username, email, password, realname) VALUES ('$usern','$email','$password','$name')"))
{
?>
<script> alert ('Successfully registered'); </script>
<?php
}
}else {
?>
<script> alert ('The Password you entered, doesnt match.. Please fill in the same password'); </script>
<?php
}
}
else {
?>
<script> alert('Username or E-mail already exist'); </script>
<?php
}
}
?>
and this is for require.inc.php
<?php
global $username;
//require 'dconn.php';
session_start();
$_SESSION["username"] = $username;
$connection = mysqli_connect("localhost","root","", "test") or die(mysqli_error());
// Check Login
if (isset($_SESSION['username']) and isset ($match['userid']))
{
$Selection = "SELECT * FROM $user_table WHERE username='$username'";
$selectQuery = mysqli_query($connection, $Selection);
if ($selectQuery != false)
{
while ($fetchD = mysqli_fetch_assoc($selectQuery))
{
$usernn = $fetchD['username'];
$email = $fetchD['email'];
$uid = $fetchD['userid'];
}
} else {
echo mysqli_error();
}
}
?>
#suggestion, create session after user login and authorized then for each page start session and take session which you created and perform SQL queries using that session variable.
for example :
$_SESSION['user_name']=$row['username'];
for each page:
session_start();
$user_name=$_SESSION['user_name'];
SQL query
mysqli_query($con,"SELECT * FROM users where column_name='$user_name'");
I think you need to include dconn.php file in all files where you want to perform the mysql operation. If you have included it only in require.inc.php then you you it in all your other files.
I trying to get work my new login system, I made a simple password with and put hashed pass to my MySQL table with the next code
makepass.php
<?php
$password = "testpass";
$hash = password_hash($password, PASSWORD_DEFAULT);
echo $hash;
?>
dologin.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include('includes/functions.php');
session_start();
if(isset($_POST['login'])) {
if(isset($_POST['username'])) {
if(isset($_POST['password'])) {
$username = $_POST['username'];
$dbconn = mysqli_query($query, "SELECT * FROM cm_users WHERE Username = '$username'") or die(mysqli_error($query));
foreach ($dbconn as $user) {
if (password_verify($_POST['password'], $user['Password'])) {
$_SESSION['user'] = $user['Username'];
} else {
echo 'Invalid password!';
}
}
} else {
echo 'Invalid username!';
}
}
}
?>
So i tried to login with "testpass" and whoala: invalid password!
Any idea? Afaik its should be okay, i dont see any syntax or other problem.
You shouldn't be a foreach for this, but first to query, fetch the array (which you're not using) and then comparing that to the row's password.
Sidenote: Replace the ("xxx", "xxx", "xxx", "xxx") with your own credentials. However, using $query isn't a word you should use as a connection variable, because it is quite confusing.
(Even I was confused when writing my answer). Use $connection or $conn and I have changed them here, so please use that instead.
$conn = new mysqli("xxx", "xxx", "xxx", "xxx");
if ($conn->connect_error) {
die('Connect Error (' . $conn->connect_errno . ') '
. $conn->connect_error);
}
if(isset($_POST['login'])) {
$username = $_POST['username']; // you could use a conditional !empty() here
$password = $_POST['password']; // here also
$query = "SELECT * FROM cm_users WHERE Username = '".$conn->real_escape_string($username)."';";
$result = $conn->query($query);
// error checking on the query
if (!$result) {
echo "<p>There was an error in query: $query</p>";
echo $conn->error;
}
$row_hash = $result->fetch_array();
if (password_verify($password, $row_hash['Password'])) {
echo "Welcome!";
}
else{
echo "Invalid";
}
}
You can then add the other goodies after, once you've had success.
Sidenote: Make absolutely sure that your POST arrays do hold values and contain no whitespaces. If there are, use trim().
I.e.:
$username = trim($_POST['username']);
$password = trim($_POST['password']);
Check for errors on your query also:
http://php.net/manual/en/mysqli.error.php
And error reporting:
http://php.net/manual/en/function.error-reporting.php
$dbconn = mysqli_query($query, "SELECT * FROM cm_users WHERE Username = '$username'") or die(mysqli_error($query));
should look more like
$userQuery = mysqli_query($variableToConnectToDatabase, "SELECT * FROM cm_users WHERE Username = '$username' AND Password='$password' LIMIT 1 ")
Not sure what your main goal is. Did you want the user to be able to put in their own password, or is the password supposed to be constant?
Try Edit dologin.php to this.....
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include('includes/functions.php');
if(isset($_POST['login'])) {
if(isset($_POST['username'])) {
if(isset($_POST['password'])) {
$username = $_POST['username'];
$hash = password_hash($_POST['password'], PASSWORD_DEFAULT);
$dbconn = mysqli_query($query, "SELECT * FROM cm_users WHERE Username = '$username'") or die(mysqli_error($query));
foreach ($dbconn as $user) {
if ($hash == $user['Password']) {
$_SESSION['user'] = $user['Username'];
} else {
echo 'Invalid password!';
}
}
} else {
echo 'Invalid username!';
}
}
}
?>
I cant seem to validate right when i have an empty field or when the username is wrong or doesnt match. please any help or pointing me would be very helpful. I tried (empty but it doesnt seem to work when i fill in one field and the other is empty its says all fields are empty. and for the wrong credentials its not working at all.
INDEX.PHP
<?php
session_start();
include_once 'php/classes/class.user.php';
$user = new User();
$log = $_SESSION['uid'];
if ($user->get_session($log)){
header("Location: profile.php?uid=".$log."");
}
if (isset($_REQUEST['submit'])) {
extract($_REQUEST);
$login = $user->check_login($emailusername, $password);
if(!empty($login)){
if($emailusername != $login){
if($password != $login){
if ($login) {
// Registration Success
$log_id = $_SESSION['uid'];
header("location: profile.php?uid=".$log_id."");
}
}else
echo "Incorrect Password";
}else
echo "Incorrect Email";
}else
echo "Fill in fields";
}
?>
USERS.PHP
<?php
include "db_config.php";
class User{
public $db;
public function __construct(){
$this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
}
/*** for login process ***/
public function check_login($emailusername, $password){
$password = md5($password);
$sql2="SELECT uid from users WHERE uemail='$emailusername' or uname='$emailusername' and upass='$password'";
//checking if the username is available in the table
$result = mysqli_query($this->db,$sql2);
$user_data = mysqli_fetch_array($result);
$count_row = $result->num_rows;
if ($count_row == 1) {
// this login var will use for the session thing
session_start();
$emaildb == $_SESSION['uemail'];
$_SESSION['login'] = true;
$_SESSION['uid'] = $user_data['uid'];
return true;
}
else{
return false;
}
}
/*** for showing the username or fullname ***/
public function get_fullname($uid){
$sql = "SELECT * FROM users WHERE uid = $uid";
$result = mysqli_query($this->db, $sql);
$user_data = mysqli_fetch_array($result);
echo $user_data['fullname'], "<br/>";
echo $user_data['uemail'], "<br/>";
echo $user_data['uid'], "<br/>";
}
public function check_user($uid){
$sql5 = "SELECT * from users WHERE uid='$uid'";
$result1 = mysqli_query($this->db, $sql5);
$count_row1 = $result1->num_rows;
return ($count_row1 == 1);
}
/*** starting the session ***/
public function get_session(){
return $_SESSION['login'];
}
public function user_logout() {
$_SESSION['login'] = FALSE;
session_destroy();
}
}
Based on what you have, this is what you would need.
session_start();
include_once 'php/classes/class.user.php';
$user = new User();
// You need a conditional incase this session isn't set
$log = (isset($_SESSION['uid']))? $_SESSION['uid']:false;
if($log !== false && $user->get_session($log)){
header("Location: profile.php?uid=".$log."");
exit;
}
if(isset($_POST['submit'])) {
// This function should be validating your login so you don't need
// any comparisons after the fact.
$login = $user->check_login($_POST['email'], $_POST['password']);
if($login !== false)
header("location: profile.php?uid=".$log_id."");
exit;
else {
foreach($user->error as $kind => $err) {
echo '<h2>'.$kind.'</h2>'.'<p>'.$err.'</p>';
}
}
}
Your user class: You can throw error reporting into this class if you want to.
class User{
public $db;
public $error;
public function __construct(){
$this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
$this->error['db'] = "Error: Could not connect to database.";
echo $this->error['db'];
exit;
}
}
/*** for login process ***/
public function check_login($emailusername='', $password=''){
// Validate that your email is a real one
if(filter_var($emailusername,FILTER_VALIDATE_EMAIL) !== false) {
$password = md5($password);
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql2 = "SELECT uid from users WHERE uemail='$emailusername' or uname='$emailusername' and upass='$password'";
//checking if the username is available in the table
$result = mysqli_query($this->db,$sql2);
$user_data = mysqli_fetch_array($result);
$count_row = $result->num_rows;
if ($count_row == 1) {
$emaildb == $_SESSION['uemail'];
// this login var will use for the session thing
$_SESSION['username'] = $user_data['uemail'];
// $_SESSION['uemail'] = $user_data['uemail'];
$_SESSION['uid'] = $user_data['uid'];
$_SESSION['login'] = true;
}
else
$this->error['account'] = 'ERROR: Invalid Username/Password';
}
else
$this->error['email'] = 'ERROR: Invalid Email Address';
return (!isset($_SESSION['uemail']))? false:true;
}
/*** for showing the username or fullname ***/
public function get_fullname($uid){
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql = "SELECT * FROM users WHERE uid = $uid";
$result = mysqli_query($this->db, $sql);
$user_data = mysqli_fetch_array($result);
echo $user_data['fullname'], "<br/>";
echo $user_data['uemail'], "<br/>";
echo $user_data['uid'], "<br/>";
}
public function check_user($uid){
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql5 = "SELECT * from users WHERE uid='$uid'";
$result1 = mysqli_query($this->db, $sql5);
$count_row1 = $result1->num_rows;
return ($count_row1 == 1);
}
/*** starting the session ***/
public function get_session(){
return $_SESSION['login'];
}
public function user_logout() {
$_SESSION['login'] = FALSE;
session_destroy();
}
}
$login is a boolean variable, while $emailusername and $password are strings, why you compare them.
i tried to put username & password dynamically but
It doesnt work with stored username & password in DB and stays on same page....
really depressed.
<?php include "../db/db_connection.php";
$username = $_POST['txt_username'];
$pwd =$_POST["txt_pwd"];
if(empty($username) || $username == ""){
header("location:index.php?err_msg=1");
exit;
}
if(empty($pwd) || $pwd == ""){
header("location:index.php?err_msg=2");
exit;
}
$sql = "SELECT username,password FROM users WHERE username= '$username' and password= '$pwd'";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result)==1){
header("location:dashboard.php");
}
else{
header("location:index.php?err_msg=3");
}
if($_REQUEST['txt_username'] == $username && $_REQUEST['txt_pwd'] == $pwd){
$_SESSION['txt_username'];
$_SESSION['txt_pwd'];
header("Location:dashboard.php");
}
else{
header("Location:index.php");
}
?>`
Those lines doesn't nothing..
$_SESSION['txt_username'];
$_SESSION['txt_pwd'];
maybe:
$_SESSION['txt_username'] = $user;
$_SESSION['txt_pwd'] = ...;
?
You can try this, I am not sure if this is exactly what you are looking for...
<?php session_start();
$username = $_POST['txt_username'];
$pwd =$_POST["txt_pwd"];
if(empty($username) || $username == ""){
header("location:index.php?err_msg=1");
exit;
}
if(empty($pwd) || $pwd == ""){
header("location:index.php?err_msg=2");
exit;
}
$sql = "SELECT username,password FROM users WHERE username= '$username' and password= '$pwd'";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result)==1){
$_SESSION['txt_username'] = $username;
$_SESSION['txt_pwd'] = $pwd;
header("location:dashboard.php");
}
else{
header("location:index.php?err_msg=3");
}
header("Location:index.php"); // if it stays on the same page remove this line
?>
I restructured your code to look more clean.
Also I suggest you to avoid using mysql and start using mysqli (or PDO) to avoid SQL injection attacks.
<?php session_start();
if(isset($_SESSION['txt_username']) && !empty($_SESSION['txt_username'])) {
//If we enter here the user has already logged in
header("Location:dashboard.php");
exit;
}
if(!isset($_POST['txt_username'])) {
header("location:index.php?err_msg=1");
exit;
}
else if(!isset($_POST["txt_pwd"])) {
header("location:index.php?err_msg=2");
exit;
}
$username = $_POST['txt_username'];
$pwd = $_POST["txt_pwd"];
//We use MYSQL with prepared statements BECAUSE MYSQL IS DEPRECATED
$mysqli = new mysqli('localhost', 'my_bd_user', 'mi_bd_password', 'my_bd');
$sql = "SELECT 1 FROM users WHERE username= ? and password = ?";
$stmt = $mysql->prepare($sql);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
if(!empty($result)) {
//IF we enter here user exists with that username and password
$_SESSION['txt_username'] = $username;
header("location:dashboard.php");
exit;
}
else{
header("location:index.php?err_msg=3");
}
Try it.
I checked your code and found everything is correct .I wold like you to add connection file on this.
Like
$username = "root";
$password = "password";//your db password
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("db name",$dbhandle)
or die("Could not select Database");
Thanks
Try below code :
i have reviewed and changed your code :
<?php session_start();
mysqli_connect("locahost","username","password");
mysqli_select_db("database_name");
$username = trim($_POST['txt_username']);
$pwd = trim($_POST["txt_pwd"]);
if($username == ''){
header("location:index.php?err_msg=1");
exit;
}
if($pwd == ""){
header("location:index.php?err_msg=2");
exit;
}
$sql = "SELECT `username`,`password` FROM users WHERE `username`= '".$username."' and password= '".$pwd."'";
$result = mysqli_query($sql);
if(mysqli_num_rows($result)>0){
$_SESSION['txt_username'] = $username;
$_SESSION['txt_pwd'] = $pwd;
header("location:dashboard.php");
}
else{
header("location:index.php?err_msg=3");
}
?>