PHP session does not work - php

Hey guys I am new to PHP and trying to figure out how to implement $_session in a very basic login system:
<?php
session_start();
include 'dbconn.php';
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = $conn->query($sql);
$row = $result->fetch_object();
if($username == "$row->username" && $password == "$row->password") {
$_SESSION['loggedin'] = "$username";
header('Location: admin.php');
} else {
header('Location: index.php?msg=wrong-username-or-password');
}
The problem is that when if I use local variables like:
$admin_userName = 'admin';
$admin_password = '1234';
and then making the comparison
if($username == "$adminusername" && $password == "$adminpassword") {
$_SESSION['loggedin'] = "$username";
header('Location: admin.php');
The $_session works perfect. But when I use this:
if($username == "$row->username" && $password == "$row->password") {
$_SESSION['loggedin'] = "$username";
header('Location: admin.php');
The session does not work. Without session the above statement works perfectly!
login.php
<?php
session_start();
include 'dbconn.php';
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = $conn->query($sql);
$row = $result->fetch_object();
if($username == $row->username && $password == $row->password) {
$_SESSION['loggedin'] = $username;
header('Location: apptify.php');
} else {
header('Location: index.php?msg=wrong-username-or-password');
}
logout.php
<?php
session_start();
unset($_SESSION['loggedin']);
header('Location: index.php');
?>
I am really lost, any help is appreciated.

The problem is that when if I use local variables like:
$admin_userName = 'admin';
$admin_password = '1234';
and then making the comparison
if($username == "$adminusername" && $password == "$adminpassword") {
The problem is that, you're using:
$admin_userName = 'admin';
$admin_password = '1234';
then using:
if($username == "$adminusername" && $password == "$adminpassword")
^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^
You forgot the underscores and not matching the variables lettercase.
Variables are case-sensitive.
if($username == "$admin_userName" && $password == "$admin_password")
My test script, with success:
<?php
session_start();
$DB_HOST = 'xxx';
$DB_USER = 'xxx';
$DB_PASS = 'xxx';
$DB_NAME = 'xxx';
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME)
or die(mysqli_connect_error());
$_POST['username'] = "John";
$username = $_POST['username'];
$_POST['password'] = "Johnny";
$password = $_POST['password'];
$_SESSION['loggedin'] = "$username";
echo $username; // echo'd John
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = $con->query($sql);
$row = $result->fetch_object();
if($username == "$row->username" && $password == "$row->password") {
$_SESSION['loggedin'] = "$username";
// header('Location: admin.php');
echo "Match!";
} else {
// header('Location: index.php?msg=wrong-username-or-password');
echo "No match.";
}
I need to point out that:
You should look into using mysqli with prepared statements, or PDO with prepared statements, they're much safer.
In regards to password storage.
If you're not already hashing passwords rather than what may be a plain text method you may be using, I suggest you look into CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.

It should be without quotes:
if($username == $row->username && $password == $row->password) {
$_SESSION['loggedin'] = $username;
header('Location: index.php');
}

Related

How do I add Login Details confirmation if incorrect?

How do I add Login Details confirmation if incorrect? what I want to happen is when the user puts his/her credentials their userID and Password are correct but the user type is wrong if the user presses the login button it will say "incorrect credentials" and same goes with userID and Password if they input the wrong credentials
<?php
include "includes/config.php";
session_start();
if(isset($_POST['loginbutton'])){
$username = $_POST['username'];
$password = $_POST['password'];
$usertype = $_POST['usertype'];
if ($username != "" && $password != ""){
$sql_query = "SELECT * FROM tbl_useraccounts WHERE employee_id='".$username."' and password='".$password."' and usertype='".$usertype."'";
$result = mysqli_query($con,$sql_query);
while ($row=mysqli_fetch_array($result)) {
if ($row['employee_id']==$username && $row['password']==$password && $row['usertype']=='Admin'){
$_SESSION['username'] = $_POST['username'];
header('location: home.php');
}
elseif ($row['employee_id']==$username && $row['password']==$password && $row['usertype']=='SuperAdmin') {
$_SESSION['username'] = $_POST['username'];
header('location: HomeForSuperAdmin.php');
}
}
}
}
?>
Dharma Is correct!
You are wide open to SQL Injections and should use parameterized prepared statements instead of manually building your queries!
If you embed a string in some SQL targeting MySQL, you must escape the string with MySQL's function for this purpose (mysqli_real_escape_string) and trigger db query to input on failed login.
Modified code:
<?php
include "includes/config.php";
session_start();
if(isset($_POST['loginbutton'])){
$username = $_POST['username'];
$password = $_POST['password'];
$usertype = $_POST['usertype'];
$loginFlag = true;
if ($username != "" && $password != ""){
$sql_query = "SELECT * FROM tbl_useraccounts WHERE employee_id='".$username."' and password='".$password."' and usertype='".$usertype."'";
$result = mysqli_query($con,$sql_query);
while ($row=mysqli_fetch_array($result)) {
if ($row['employee_id']==$username && $row['password']==$password && $row['usertype']=='Admin'){
$_SESSION['username'] = $_POST['username'];
header('location: home.php');
$loginFlag = true;
}
elseif ($row['employee_id']==$username && $row['password']==$password && $row['usertype']=='SuperAdmin') {
$_SESSION['username'] = $_POST['username'];
header('location: HomeForSuperAdmin.php');
$loginFlag = true;
}
else {
$loginFlag = false;
}
}
}
if($loginFlag == false){
#real_escape_string is used to prevent sql injection
$username = real_escape_string($_POST['username']);
$password = real_escape_string($_POST['password']);
$usertype = real_escape_string($_POST['usertype']);
# query assume table name log
$sql_query = "INSERT INTO log (username, password, usertype, ip_address)
VALUES ('$username ', '$password ', '$usertype ', '".$_SERVER['REMOTE_ADDR']."')";
}
}
?>

php admin and user account doesn't work

I have a login form. I have in my table of the database two records: admin and user. If you login if admin you must go to admin_area.php. this is not working, he always log in if user.
If you login if user this works.
The first part of the script is not working and don't run.
Can someone help me?
thanks in advance.
<?php
//first part: this is not working
session_start();
//if (isset($_POST['submit'])) {
$a_username = $_POST ['username'];
$a_password = md5( $_POST ['password']);
if($a_username == "admin" && $a_password=="intel")
{
include 'connect.php';
$sqli = "SELECT * FROM users WHERE username='$a_username' AND password='$a_password' ";
$numrows = mysqli_query($link, $sqli) or die(mysqli_error());
$username = 'username';
$password = 'password';
//Add some stripslashes
$username = stripslashes($username);
$password = stripslashes($password);
//Check if username and password is good, if it is it will start session
if ($username == $a_username && $password == $a_password)
{
$_SESSION['username'] = 'true';
$_SESSION['username'] = $username;
//Redirect to admin page
header("Location: admin_area.php");exit();
}
}
//second part: this works
$username = $_POST ['username'];
$password = md5( $_POST ['password']);
if($username&&$password)
{
include 'connect.php';
$query = "SELECT * FROM users WHERE username='$username' AND password='$password' ";
$numrows = mysqli_query($link, $query) or die(mysqli_error());
if ($numrows != 0)
{
/
while ($row = mysqli_fetch_assoc ($numrows))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if ($username==$dbusername&&$password==$dbpassword)
{
echo "you are log in <a href='user.php'>click here for contine</a>, after 4 seconds"; header('Refresh: 4;url=user.php');
$_SESSION ['username'] = $username;
}
else
echo "<h3>incorrect password, <a href='index.php'>click here</a></h3>";
}
else
die ("text");
}
else
die ("text");
//}
?>
$a_password = md5( $_POST ['password']);
if($a_username == "admin" && $a_password=="intel")
This condition is not valid, because
$a_password = md5( $_POST ['password'])
is first converted to md5 format and then checked $a_password=="intel"
$a_password is now in md5 format and intel is normal string. For this first try to match normal $a_password like
$a_password = $_POST ['password']
and write your variable into your condition as like
$a_password = md5( $_POST ['password'])

PHP checking empty fields Login [duplicate]

This question already has answers here:
PHP: check if any posted vars are empty - form: all fields required
(9 answers)
Closed 2 years ago.
I have a select action and I want to check if the fields username and password are both empty. My issue is that if one of them is empty echo msg pops but, but if both are empty it goes straight to the next page.
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
if ($_POST['submit']) {
include_once("connexion.php");
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$sql = "SELECT id, username, password FROM users where username = '$username' and password ='$password'";
$query = mysqli_query($dbCon,$sql);
if ($query) {
$row = mysqli_fetch_row($query);
$userId = $row[0];
$dbUsername = $row[1];
$dbPassword = $row[2];
}
if ($username == $dbUsername && $password == $dbPassword) {
$_SESSION['username'] = $username;
$_SESSION['id'] = $userId;
header('location:../index-2.php');
} else {
echo "wrong username or password";
}
}
?>
Edit : I used Dharmesh Goswami solution :
if ($username == $dbUsername && !empty($username) && $password == $dbPassword && empty($password) )
It works like a charm ! Thank you.
Just check in if condition that both are not empty.
if ($username == $dbUsername && !empty($username) && $password == $dbPassword && !empty($password) )
{
$_SESSION['username'] = $username;
$_SESSION['id'] = $userId;
header('location:../index-2.php');
}else
{
echo "wrong username or password";
}
You can apply empty() condition right after form posted.
if (isset($_POST['submit'])) {
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$username = trim($username);
$password = trim($password);
if (empty($username) || empty($password)) {
// Print your error.
}
}
|| will check if any one or both the fields are empty.
You can use the empty() function to check if input string is empty or not. To check if one of the fields is empty, you could use the XOR(^) operator. Failing which, the control should pass to AND(&&) operator which checks if both the fields are empty. If that fails too, you could say that none of the fields is empty. Hope this helps.
if(isset($_POST['submit']){
if(empty($_POST['username'] ^ empty($_POST['password']){
// code here to perform task if one field is left empty
} else if(empty($POST['username'] && empty($_POST['password']){
// code here to perform task if both fields are empty
} else {
// code here to perform task when none of the fields is empty
}
}
You do like that
extract($_POST);
if($_POST['submit']) :
if($Username == "" && $Password == ""):
$_SESSION['error'] = "Can't Be Blanked User Name Or Password";
endif;
endif;
I would suggest using mysqli_real_escape_string
if(!empty($_POST['username'])) $username = mysqli_real_escape_string($dbCon, $_POST['username']);
same for password
$sql = 'SELECT id, username, password FROM use...';
$result = $dbCon->query($sql);
$count = $conn->affected_rows;
if ($count == 1)
{
$_SESSION['username'] = $username;
$_SESSION['id'] = $userId;
header('location:../index-2.php');
}else echo "wrong username or password";
also, wouldn't save username in sessions. Look up more on securing session.

How i connect my login.php like my register.php?

I have just connected my register.php to mysql database. and i try connect my login.php but i cant.
this is my connected register.php
$connect = mysqli_connect("mysql13.000webhost.com","a2955851_SW","********");
if(isset($_POST['submit']))
{
$username = mysqli_real_escape_string($connect, $_POST['username']);
$pass = mysqli_real_escape_string($connect, $_POST['pass']);
$pass1 = mysqli_real_escape_string($connect, $_POST['pass1']);
$email = mysqli_real_escape_string($connect, $_POST['email']);
if($username && $pass && $pass1 && $email)
{
if($pass==$pass1)
{
mysqli_select_db($connect, "a2955851_SW");
$query = mysqli_query($connect, "INSERT INTO users VALUES('$username','$pass','$email');");
echo "You have been registered.";
}
else
{
echo "Password must match.";
}
}
else
{
echo "All fields are required.";
}
}
and this is login.php i tryed connect this but...
<?php
$connect = mysqli_connect("mysql13.000webhost.com","a2955851_SW","********");
session_start();
if(isset($_POST['login']))
{
$username = mysqli_real_escape_string($connect, $_POST['username']);
$password = mysqli_real_escape_string($connect, $_POST['password']);
if($username && $password)
{
mysqli_select_db($connect, "a2955851_SW");
$login = mysql_query("SELECT * FROM users WHERE username = '$username'");
while($log=mysqli_fetch_assoc($login))
{
$dbusername = $log['username'];
$dbpassword = $log['password'];
}
if($username==$dbusername && $password==$dbpassword)
{
$_SESSION['username'] = $dbusername;
$_SESSION['password'] = $dbpassword;
header("location:members.php");
}
else
{
header("location:index.php?notify=Incorrect Username or Password.");
}
}
else
{
header("location:index.php?notify=ALL field are required.");
}
}
?>
i tried connect login.php similarly I do not know
You have mixed mysql & mysqli. Use only one. Change
$login = mysql_query("SELECT * FROM users WHERE username = '$username'");
to
$login = mysqli_query($connect, "SELECT * FROM users WHERE username = '$username'");
I am not really sure but try changing the following line:
$password = mysqli_real_escape_string($connect, $_POST['password']);
to
$password = $_POST['password'];
this is because at the later part of your script, you will be checking
if($username==$dbusername && $password==$dbpassword)
and if $password is escaped, $dbpassword will not be and the same password might result in a false comparison.
Lets say the actual password is 12"3, $password will be 12\"3 and $dbpassword will be 12"3 if $password is escaped.
The best way is to make a connection file and include in all php file you want to connect to database. So you don't need to check in every page and run your query before just below connection string to make sure its working
$query = mysqli_query($connect, "INSERT INTO users VALUES('$username','$pass','$email');");
echo "You have been registered.";
}

Password correct but error message saying its incorrect

I can't figure out what is wrong with program. The password I know is correct but for some reason I am receiving an error saying it is incorrect.
here is my signup.php
$UserName = $_POST['UserName'];
$password = $_POST['password'];
$msd5Password = $md5[$password];
$email = $_POST['email'];
if ($UserName == null || $password == null || $email == null) {
echo 'Please Fill In All The Values';
}
else {
$sql = mysql_query("SELECT * FROM login WHERE email = '$email'");
$numrows = mysql_num_rows($sql);
if($numrows !=0)
{
die("There already is an account created with the email you entered.");
}
else
{
mysql_connect("localhost", "root") or die (mysql_error);
mysql_select_db ("thereview");
mysql_query("INSERT INTO login (UserName, password, email) VALUES ('$UserName', '$md5Password', '$email')")
or die(mysql_error());
header("Location:login.php");
}
}
And here is my login.php
session_start();
$UserName = $_POST['UserName'];
$password = $_POST['password'];
if($UserName == null|| $password == null) {
echo 'Please fill in UserName and Password';
}
else{
mysql_connect("localhost", "root") or die (mysql_error);
mysql_select_db ("thereview");
$query = mysql_query ("SELECT * FROM login WHERE UserName = '$UserName'");
$numrows = mysql_num_rows($query);
if($numrows != 0) {
while($row = mysql_fetch_assoc($query)) {
$dbEmail = $row['email'];
$dbUserName = $row['UserName'];
$dbPassword = $row['password'];
$dbId = $row['id'];
}
if($UserName = $dbUserName && md5($password) == $dbPassword) {
$_SESSION['UserName'] = $dbUserName;
$_SESSION['email'] = $dbEmail;
}
else {
echo 'UserName or Password is incorrect';
}
}
else {
echo 'User does not exist, Create an Account';
}
}
Looks like you have a typo here:
$msd5Password = $md5[$password];
should probably be:
$md5Password = md5($password);
Keep in mind MD5 is not good for password security any longer and you have VERY POOR security for this script, open to injection and other issues.
Are you sure about this?
$msd5Password = $md5[$password];
I think it should be:
$md5Password = md5($password);
$msd5Password = $md5[$password]; should probably read: $md5Password = md5($password); (careful about the details - dollars and parenthesis)
$UserName = $dbUserName should probably be $UserName == $dbUserName
In the sign up script you write $md5$password
I'm not strong in php, but shouldn't that be md5($password) as you write in the login script?
if($UserName **=** $dbUserName && md5($password) == $dbPassword)
will always give you false...
Try $UserName **==** $dbUserName instead.
Try this. You need to put parenthesis around these commands to make sure that its a test of only those values. Also where you have $UserName = $dbUserName you need to have it be == instead of =. Otherwise it will always be set to true rather then be testing it.
if(($UserName == $dbUserName) && (md5($password) == $dbPassword))
Also, at the top the code you have is this:
$msd5Password = $md5[$password];
You have two typos in there. First of all your variable later on is md5Password so you need to remove the s. Also the syntax for md5 is md5($password). Finally md5 is a function not a variable so you don't need the $.
Correct Syntax:
$md5Password = md5($password);
I hope this is helpful!

Categories