echoing wrong else in php - php

Whenever I input wrong username, the resulting page gives the second else output. I want the first else to be displayed on the screen if a user types in wrong username and the second else to be displayed when someone tries to go in the login page directly from the url without inputting any name. And yes session_start(); has been declared on top of both the pages.
<?php
if (isset($_POST["submit"]))
{
$username = $_POST["username"];
$conn = new mysqli("localhost", "root", "", "test");
$result = $conn->query("select name from students where name = '$username'");
if ($result->num_rows > 0)
{
$_SESSION["username"] = $username;
echo "You are logged in. This is the welcome page. Welcome user: " . $username;
}
else
{
echo "Invalid username. Try again.";
}
$conn->close();
}
else
{
echo "Come through proper ways.";
}
?>

Possible issues
In general, you omitted some error management that could lead to unexpected behavior, which breaks the logic of your conditions.
You must check $_POST['username'], consider possible to receive $_POST['submit'] without an username (the web is full of surprises). The best way to differentiate missing username and bad username is to check it directly with isset() and empty() for instance.
You must check that the database connection succeeded to avoid exceptions with conn->connect_errno.
You must check if $result evaluates to false which would mean that there is a query error.
You may escape $username before inserting it into the request, I don't know how mysqli manages SQL injections.
Possible solution
<?php
if ( isset($_POST['submit']) && isset($_POST['username']) && !empty($_POST['username']) ) {
$conn = new mysqli("localhost", "root", "", "test");
$username = mysqli_real_escape_string($conn, $_POST["username"]);
// check connection
if ( $conn->connect_errno ){
die("Data access denied ([".$conn->connect_errno."] ".$conn->connect_error.")");
}
$result = $conn->query("select name from students where name = '$username'");
// check for query errors
if (!$result) {
die("Data access denied (invalid query)");
}
// ...
} else {
echo "Come through proper ways.";
}

try with following codes
<?php
if(isset($_POST["submit"] && array_filter($_POST) && $_POST['username']){
$conn = new mysqli("localhost", "root", "", "test") or die('Database Connection Failure ' . (($conn->connect_errno) ? $conn->connect_error : ''));
$username = mysqli_real_escape_string($conn, $_POST['username']);
$result = $conn->query("select name from students where name = '{$username}'");
if($result->num_rows > 0){
// success
$_SESSION["username"] = $username;
echo "You are logged in. This is the welcome page. Welcome user: " . $username;
}else{
echo "Invalid username. Try again.";
}
$conn->close();
}else{
echo "Come through proper ways.";
}

Related

PHP Login script only works with usernames known to mysql

This script should get some Variables of a submit form. Then it should check them from the DB and see if password and username match, if not it should send them back to the login page.
I already tried letting it check if the username exist via:
$this = "Select name from user where name = '".$_POST['name']"'";
$query = mysqli_query($conn,$this);
while( $row = mysqli_fetch_assoc($query)){
if (empty($row['name']){
do this;
}
}
But still got a blank page.
<?php
include "private/dbconnection.inc.php";
$conn = mysqli_connect($servername, $username, $password, $db);
if(!$conn){
die ("Verbindung fehlgeschlagen: ". mysqli_connect_error());
}
$selectpw = "SELECT * from user where name = '".$_POST['name']." ' ";
$pwcheck = mysqli_query($conn,$selectpw);
$selectname = "SELECT name from user where name = '".$_POST['name']."'";
$namecheck = mysqli_query($conn,$selectname);
while ( $row = mysqli_fetch_assoc($pwcheck)){
if ( $_POST['password'] === $row['password'] && $_POST['name'] === $row['name'] ){
header("Location:https://myhost.de/xxx/this/user.php");
}
else{
header("Location:https://myhost.de/xxxx/prototyp1/");
}
}
mysqli_close($conn);
?>
The script should check if the user is valid for login if hes not he should be send back to login. If hes valid he gets to another page.
But it only works with usernames the mysql knows with other usernames im stuck on the php page and it just shows a blank screen.
As Obsidian said, your code is potentially vulnerable to SQL injection, therefore it would be more suitable to use PDO. This can be achieve like so in the basic code example below.
<?php
include "private/dbconnection.inc.php";
try {
$db = new PDO('host=' . $server_name . ';dbname=' . $database . 'charset=utf-8;', $username, $password);
}
catch(PDOException $e)
{
throw $e; // Throw the PDOException if something failed
}
if(isset($_POST['username']) && isset($_POST['password']))
{
if(!empty($_POST['username'] && !empty($_POST['username'])
{
$query = $db->prepare('SELECT password FROM users WHERE username = ?');
$query->bindParam(1, trim($_POST['username']));
if($query->execute())
{
$password = $query->fetchColumn();
if($_POST['password'] == $password)
{
header('Location: https://myhost.de/xxx/this/user.php');
} else {
header('Location: https://myhost.de/xxxx/prototyp1/');
}
}
}
}
?>

Every entered username and password works in PHP login

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

PHP login code error with mysql_query()

I've been following a login system tutorial. You can find it here. There are 2 parts of coding C# and PHP. The C# part is working fine but my PHP part returning error. Here is my PHP code:
<?php
$servername = getenv('IP');
$username = getenv('C9_USER');
$passwordp = "";
$database = "game_database";
$dbport = 3306;
// Create connection
mysql_connect($servername, $username, $passwordp, $dbport)or die("Cant Connect to server");
mysql_select_db($database) or die("Cant connect to database");
// Check connection
$Email = $_REQUEST["Email"];
$Password= $_REQUEST["Password"];
if (!$Email || !$Password){
echo"Email or password must be used";
}
else{
$SQL = "SELECT * FROM 'users' WHERE Email = '" . $Email ."'";
$result_id = #mysql_query($SQL) or die("Database Error");
$Total = mysql_num_rows($result_id);
if ($Total){
$datas = #mysql_fetch_array($result_id);
if (strcmp($Password, $datas["Password"])){
$sql2 = "SELECT Characters FROM users WHERE Email = '" . $Email ."'";
$result_id2 = #mysql_query($sql2) or die("Database Error!!!");
while ($row = mysql_fetch_array($result_id2)){
echo $row ["Characters"];
echo ":";
echo "Success";
}
}
else{
echo "WrongPassword";
}
}else {
echo "NameDoesNotExist";
}
}
?>
It seems the error comes from $result_id but I'm not sure?
You are true, the error is from $result_id, because your SQL statement has problem and there are extra stuff to fix.
You have put users table in two single quotes, it is wrong.
Your code is:
$SQL = "SELECT * FROM 'users' WHERE Email = '" . $Email ."'";
It should be with out quotes:
$SQL = "SELECT * FROM users WHERE Email = '" . $Email ."'";
You have wrote:
if ($Total){
It should check how many users record found, typically it should find only 1 record and return 1, therefore change it to:
if ($Total == 1){
Note1:
But when this is said, it does not mean the code is perfect, you should further develop your code to fulfill nowadays requirement. I would suggest you think of password hashing, use mysqli or PDO in sted of mysql and input sensitization. I would suggest you look at this link it describes some of the things I mentioned.
Note2:
I was able to write you a total solution with mysqli/PDO etc, but I wanted only to point the errors I have catch so far in your code so you can learn from your mistakes and develop your self.
And in general read about security principles, check this page.
Link1: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
Link2: https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
This is another simple way where you can create user log in, it is
more secure than the one you have at the moment. And you should
protect your code from sql injections.
<?php
if (isset($_POST['email'], $_POST['password']) === true )
{
require 'connection.php';
$email = mysqli_real_escape_string($connection,$_POST['email']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$sql = "SELECT * FROM users WHERE email= '$email'";
$result = mysqli_query($connection,$sql);
if (mysqli_num_rows($result))
{
if( $email == $row['email'] && $password == $row['password'])
{ //use session to check if user is logged in
if (!isset($_SESSION['loggedin']))
{
//you can set session of user's log in details
//you can redirect to user profile
}
else
//already log in, redirect to user profile
}
else
echo "Incorrect Email or Password.";
}
else
echo "Incorrect Username or Password.";
mysqli_close($connection);
}
else
{
echo "Oops, something went wrong!";
?>

PHP-MySQL Login system

This is the first time I'm using PHP and MySQL to make a login system where a person can enter username and password and the php scripts checks if the username and password exists in the database.
When the user enters the correct info It displays the "SUCCESSFULLY LOGIN TO USER PROFILE PAGE..." message which is all good. But if the user enters in the wrong info, the "SORRY...YOU ENTERED WRONG ID AND PASSWORD...PLEASE RETRY..." message should appear but the page is blank. Why is that?
<?php
define('DB_HOST','localhost');
define('DB_NAME','test'); //name of database
define('DB_USER','root'); //mysql user
define('DB_PASSWORD',''); //mysql password
$con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die(mysqli_connect_error());
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
}
$db = mysqli_select_db($con,DB_NAME) or die(mysqli_connect_error());
/*
$ID = $_POST['user'];
$Password = $_POST['pass'];
*/
function SignIn(mysqli $con){
session_start(); //starting the session for user profile page
if(!empty($_POST['user'])){ //checing the 'user' name which is from Sign-in.html, is it empty or have some text
$query = mysqli_query($con,"SELECT * FROM UserName where userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysqli_connect_error());
$row = mysqli_fetch_array($query) or die(mysql_error());
if(!empty($row['userName']) AND !empty($row['pass'])){
$_SESSION['userName'] = $row['pass'];
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";
}
else{
echo "SORRY...YOU ENTERED WRONG ID AND PASSWORD...PLEASE RETRY...";
}
}
}
if(isset($_POST['submit'])){
SignIn($con);
}
?>
Firstly, I have to state that your code is highly prone to SQL injection <= do read that, not to mention storing passwords in plain text which is highly discouraged.
Do not store passwords in plain text, you will eventually get hacked.
Consult my footnotes about all of the above, regarding injection and password storage.
You're also mixing MySQL APIs with mysql_error() which doesn't intermix with mysqli_ functions. It needs to be mysqli_error($con).
Now, your code is failing because of this line:
if(!empty($row['userName']) AND !empty($row['pass']))
Even though a person enters a wrong or inexistant username and/or password, it will still remain TRUE because those rows are NOT empty.
Therefore it never gets to enter the else part of your script.
To get you started, here is what you need to do:
Replace:
if(!empty($row['userName']) AND !empty($row['pass']))
with:
$row = mysqli_fetch_array($query);
$username = $row['userName'];
$pw = $row['pass'];
if($user==$username && $pass==$pw) {
// $user and $pass are from POST
// $username and $pw are from the rows
$_SESSION['userName'] = $row['pass'];
echo "Successfully logged in.";
}
else { echo "Invalid."; }
While using the following inside the SignIn() function:
$user = mysqli_real_escape_string($con,$_POST['user']);
$pass = mysqli_real_escape_string($con,$_POST['pass']);
and replacing your query with:
$query = mysqli_query($con,"SELECT * FROM UserName
where userName = '$user'
AND pass = '$pass'")
or die(mysqli_connect_error());
Footnotes:
For password storage, use CRYPT_BLOWFISH or PHP 5.5's password_hash() function.
For PHP < 5.5 use the password_hash() compatibility pack.
Plus, in regards to SQL injection, use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Edit:
Oh yea and also I changed my code to yours, but now everytime I login It displays Invalid, even with the right username and password. Any ideas?It seems to be failing the if($user==$username && $pass==$pw) if statement.
Here's what I used to test it with, you can replace the DB credentials with your own and other adjustments, since I did not use a form, but hard-coded values.
This did in fact jump in the else if an incorrect user/password was entered.
<?php
$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());
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
}
function SignIn($con){
$_POST['user'] = "John";
$user = $_POST['user'];
$_POST['pass'] = "12345";
$pass = $_POST['pass'];
// session_start(); //starting the session for user profile page
if(isset($_POST['user'])){
$query = mysqli_query($con,"SELECT *
FROM UserName where userName = '$_POST[user]'
AND pass = '$_POST[pass]'")
or die(mysqli_connect_error());
$row = mysqli_fetch_array($query);
$username = $row['userName'];
$pw = $row['pass'];
if($user==$username && $pass==$pw) {
echo "Successfully logged in.";
}
else { echo "Invalid"; }
} // brace for isset post user
} // brace for function
if(isset($_POST['submit'])){
echo SignIn($con);
}
?>
Before I get to the actually answer to you question, I would recommend you to use mysqli_real_escape_string() for both username and password. You could use PDO which does it all for you and in my opinion is less work.
The problem you have is that your forgot to add another else block on the first if statement.
if(!empty($_POST['user'])) {
// first block
if(!empty($row['userName']) AND !empty($row['pass'])) {
// first inner block
} else {
}
} else {
// this else is what your missing
}

Cannot find mistake in PHP + MySQLi register page

I am trying to build a register page using PHP and MySQLi. However, it doesn't work, and I cannot understand the issue. It was previously with no MySQL improved syntax. There is just an empty page in browser.
<?php
include ("bd.php");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['login']))
{
$login = $_POST['login'];
if ($login == '')
{
unset($login);
}
}
if (isset($_POST['password']))
{
$password=$_POST['password'];
if ($password =='')
{
unset($password);
}
}
if (empty($login) or empty($password))
{
exit ("You have entered not all of the information, go back and fill in all the fields!");
}
$login = stripslashes($login);
$login = htmlspecialchars($login);
$password = stripslashes($password);
$password = htmlspecialchars($password);
$login = trim($login);
$password = trim($password);
$myrow = mysqli_query($db,"SELECT id FROM users WHERE login='$login'");
if (!empty($myrow['id']))
{
exit ("Sorry, you entered login which is already registered . Please enter a different username.");
}
$result2=mysqli_query($db,"INSERT INTO users (login,password) VALUES('$login','$password')");
if ($result2=='TRUE')
{
echo "You have successfully signed up!";
}
else
{
echo "Failed to sign up";
}
?>
bd.php:
<?php
$db = new mysqli ("localhost","root","root","kotik");
?>
<?php
include ("bd.php");
if (mysqli_connect_errno()){echo "Failed to connect to MySQL: " . mysqli_connect_error();}
$login = isset($_POST['login'] && !empty($_POST['login'])) ? stripslashes(trim($_POST['login'])) : null;
$password = isset($_POST['login'] && !empty($_POST['login'])) ? stripslashes(trim($_POST['login'])) : null;
$password = htmlspecialchars($password);
if (empty($login) || empty($password)){exit ("You have entered not all of the information, go back and fill in all the fields!");}
$res = mysqli_query($db,"SELECT id FROM users WHERE login='$login'");
$myrow = mysqli_fetch_assoc($res);
if (!empty($myrow['id'])) {
exit ("Sorry, you entered login which is already registered . Please enter a different username.");
}
$result2 =mysqli_query($db,"INSERT INTO users (login,password) VALUES('$login','$password')");
if ($result2 == true)//use true not 'True' because 'True' is a string
{
echo "You have successfully signed up!";
}
else {
echo "Failed to sign up";
}
?>
EDIT: You should use mysqli_fetch_assoc to get an associative array which corresponds to the fetched row or NULL if there are no more rows.
You cannot use the variable $myrow like this:
$myrow['id']
You need to get the row then you can treat it like an array. It would look something like this:
$row = $myrow->fetch_row()
$row['id']
this gets the first row of the results of the query. If the query returns multiple results you can use something like this:
while($row = $myrow->fetch_row()) {
$rows[]=$row;
}
Then you use $rows as a normal array and get the individual rows 1 by 1 in a for loop, then you can use the same format:
$temp = $rows[0];
$temp['id']

Categories