Registered user say with such data login = test, password = 12345
and I try to make an input manually. I am writing a link example.com/login.php?username=test&password=12345
and by code it prints Invalid. Although checked in the database user this is there, all the data is correctly entered, but does not see it. I tried to create another, but the result is the same. Here is my code, then what is commented on, tried the first time to get the answer, the result is the same. Errors do not display.
<?php
error_reporting(E_ALL);
require_once ("connect.php");
$login = mysqli_real_escape_string($conn,$_GET['username']);
$password = mysqli_real_escape_string($conn,$_GET['password']);
$password = md5($password);
$sql = mysqli_query($conn, "SELECT * FROM login WHERE username = '$login' AND password = '$password'");
//if($sql){
// $dados = mysqli_num_rows($sql);
// echo "$dados";
// if($dados > 0){
// echo 'Success';
// }else{
// echo 'Invalid';
// }
//}
$id_user = mysqli_fetch_array($sql);
if (empty($id_user['id'])){
echo 'Invalid';
}
else {
echo 'Success';
}
mysqli_close($conn);
?>
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 -->
<?php
include "config.php";
?>
<?php
$username = $_POST['username'];
$password = $_POST['password'];
?>
<?php
$sql = "SELECT username FROM usr";
$resultuser = $conn->query($sql);
$conn->close();
$sql = "SELECT password FROM usr";
$resultpass = $conn->query($sql);
$conn->close();
?>
<?php
if ($resultuser == $username) {
if($resultpass == $password) {
echo "test";
} else {
echo "Wrong user or pass" ;
}
}
?>
Php won't send a query to mysql to check if the variable (username, and password) matches one of the rows in my mysql database.
I'm not sure what else to do
also config.php is the file which contains the code to connect to my mysql server.
you have to iterate over the obtained result as
$result = $conn->query($sql);
$resultUser= "";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$resultUser =$row['username '];
}
}
and you are doing it wrong. In order to check where the username and password match the database entry should be like :
select * from user_table
where username = 'pass_the_user_name' and password='user_password';
If this returns a row, that means this is a valid user else invalid credentials or anything.
Here is my login.php script.
When it runs, it dumps the array (error 2) of what was input, completely skipping everything (i think). I have absolutely no idea what's wrong.
<?php
include('../../content/php/base.php');
// Get data
$user = $_REQUEST['user'];
$pass = $_REQUEST['pass'];
// Encrypt password
include('../../content/php/salt.php');
$pass = crypt($pass,$salt);
// Check database for user / check session
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['user'])) {
header("Location: websiteURL");
} elseif(!empty($user) && !empty($pass)) {
$user = mysqli_real_escape_string($con, $user);
if($result = mysqli_query($con, "SELECT * FROM users WHERE `user`='".$user."' AND `pass`='".$pass."'")) {
$row_cnt = mysqli_num_rows($result);
if($row_cnt == 1) {
$row = mysqli_fetch_array($result);
$email = $row['email'];
$_SESSION['user'] = $user;
$_SESSION['email'] = $email;
$_SESSION['LoggedIn'] = 1;
header("Location: websiteURL");
} else {
echo "Error 1";
die();
}
} else {
echo "<pre>"; // dumps the array onto multiple lines instead of one
print_r($_REQUEST);
echo "</pre>";
echo "Error 2";
die();
}
} else {
echo "Error 3";
die();
}
?>
Here is the full output of the print_r($_REQUEST); :
Array
(
[user] => username
[pass] => password
[PHPSESSID] => 5958246ece69dfdff197ec46e4771aac
)
Error 2
Your query is obviously failing
if($result = mysqli_query($con, "SELECT * FROM users WHERE `user`='".$user."' AND `pass`='".$pass."'") {...}
Is $con a valid connection?
Try putting backticks around the table name users.
You should do some error checking. Take a look at the output of
// You can add this to the Error 2 block (for testing.. not production use)
echo mysqli_error($con);
This will give you an "idea" of what's going wrong, and will help others much in helping you.
Try using session_start(); before any of the includes. This ensures the server session is started
If i enter wrong password it shows 'Wrong username or Password' but if enter wrong username and correct password it shows nothing. Why ? what should i change in the code?
<?php
$name = $_POST['username'];
$password=$_POST['pwd'];
$dbc = mysql_connect('localhost', 'username', 'password') or die();
mysql_select_db("dbname") or die();
$result = mysql_query("SELECT * FROM table WHERE uname='$name'") or die(mysql_error());
while($row = mysql_fetch_array($result))
{
if($row['uname']==$name && $row['pword']==$password)
{
echo 'Successfully logged in <br />';
break;
}
else
{
echo 'Wrong username or password';
}
}
mysql_close($dbc);
?>
Because if you enter the wrong username the query returns nothing.
Then you don't get into the while loop.
You could change the query :
$result = mysql_query("SELECT * FROM table WHERE uname='".addslashes($name)."' and pword='".addslashes($password)."'");
Then use mysql_fetch_row() only once (remove your while loop).
EDIT
<?php
function hash_password($password){
$myVerySecretSalt = "pREkeSw2"; //don't use this string, create your own random one!
return md5($myVerySecretSalt.$password.$myVerySecretSalt);
}
$name = $_POST['username'];
$password = hash_password($_POST['pwd']);
$dbc = mysqli_connect('localhost', 'username', 'password') or die();
mysqli_select_db("dbname") or die();
$mysql_result = mysqli_query("SELECT * FROM table WHERE uname='".addslashes($name)."' and pword='".$password."'");
$result = mysqli_fetch_row($mysql_result);
mysqli_close($dbc);
if(!$result){
echo "Wrong username or password.";
}else{
var_dump($result);
echo "Successfully logged in.";
}
?>
EDITED for usage of MySQLi as mysql is deprecated since PHP 5.5
EDITED as for plaintext passwords.
It's never a very good thing to store passwords in plaintext in the database as they can be stolen in case of sql injection.
A way to protect your users password is to hash them, below is a basic implementation :
First create a function to hash a password :
function hash_password($password){
$myVerySecretSalt = "pREkeSw2"; //don't use this string, create your own random one!
return md5($myVerySecretSalt.$password.$myVerySecretSalt);
}
Then replace your third line $password = $_POST['pwd']; with this one : $password = hash_password($_POST['pwd']);
Here you go! (Just remember to use that same function on the password when you create the user account)
This should work correctly:
<?php
$name = $_POST['username'];
$password=$_POST['pwd'];
$dbc = mysql_connect('localhost', 'username', 'password') or die();
mysql_select_db("dbname") or die();
$result = mysql_query("SELECT * FROM table WHERE uname='$name'") or die(mysql_error());
$row= mysql_fetch_array($result)
if($row && $row['uname']==$name && $row['pword']==$password)
{
echo 'Successfully logged in <br />';
break;
}
else
{
echo 'Wrong username or password';
}
mysql_close($dbc);
?>
your previous code didn't show anything becasue row = mysql_fetch_array($result) were not finding any record, and so returning immediately false (and exied the while)
Seems like you enter a username that does not exist in that table.
Remove your while loop. Just say:
$result = mysql_fetch_assoc(mysql_query("SELECT * FROM table WHERE uname = '".mysql_real_escape_string($name)."' AND pword = '".mysql_real_escape_string($password)."'"));
if ($result) {
// Successfully logged in
} else {
// Login failed
}
Keep in mind that the mysql_real_escape_string is very important when accepting user input to avoid SQL injection.
Since you are authenticating a user, record must be unique.
Thus, you shouldn't be looping through anything:
Get rid of the loop and change your conditions
$row = mysql_fetch_array($result);
if($row['uname']==$name && $result){
if($row['pword']==$password){
echo 'Successfully logged in <br />';
}else{
echo 'Wrong Password';
}
}else{
echo 'No record found';
}
mysql_close($dbc);
I refactored your code for this one. I recommend use mysql_fecth_row instead mysql_fetch_array beacause you need just one row.
<?php
// get, validate and clean your input variables
$name = isset($_POST['username']) ? addslashes($_POST['username']) : '';
$password =isset($_POST['pwd']) ? addslashes($_POST['pwd']) : '';
// make your data base connection
$dbc = mysql_connect('localhost', 'root', '') or die();
mysql_select_db("test_mysql") or die();
// building the sql query and getting the result (remember filter by username and password)
$result = mysql_query("SELECT * FROM tb_usuario WHERE uname = '$name' AND pword = '$password'") or die(mysql_error());
// using mysql_fetch_row (remember that just one user must match in the data base if not something is wrong in register ...)
$row = mysql_fetch_row($result);
// remember 0 => id, 1 => uname, 2 => pword
if (is_array($row)) {
echo "Welcome {$row[1]}";
} else {
echo 'Wrong username or password';
}
// close your connection
mysql_close($dbc);
I'm new to PHP and programming in general, but am working on doing a login. I've got the signup page completed, and my database populates the records fine. However, when this code gets output it says I have 0 rows from the mysql_num_rows($result);... when, it should be coming back successfully showing 1 row when I input the correct username/password. Whether I put in a successful user/pass combo or not, it outputs the same.
I appreciate any help you can provide, code is listed below:
$SQL = "SELECT * FROM account WHERE username = $username AND password = md5($password)";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
echo $result;
echo $num_rows;
// CLOSE CONNECTION
mysql_close($db_handle);
// COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS PAGE
if ($result) {
if ($num_rows > 0) {
session_start();
$_SESSION['login'] = "1";
header ("Location: page1.php");
}
else {
$error_message = "Login failed. Please try again.";
echo $num_rows;
EDIT: Complete rewrite
Try this:
<?php
$host = "host";
$user = "user";
$password = "password";
$database = "database";
$username = 'jack'; /* Insert $_Post [''] here with username variable you pass. You could sanitize and validate with for example filter_var (), clean (), etc */
$password_user = 'password from jack'; // same here.
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link){
echo ("Unable to connect to database!");
}
ELSE{
$query = "SELECT * FROM account WHERE username ='$username' AND password = md5('$password_user')";
$result = mysqli_query($link, $query);
$num_rows = mysqli_num_rows($result);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
// COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS PAGE
if ($row) {
session_start();
$_SESSION['login'] = "1"; // pleae not that 1 is converted into a string value
$_SESSION['username'] = $username; // added username, just to test.
header ("Location: page1.php");
}
else {
$error_message = "Login failed. Please try again.";
echo $error_message;
}
// CLOSE CONNECTION
mysqli_close($link);
}
?>
Sample data:
CREATE TABLE account (
id INT auto_increment primary key,
username VARCHAR(30),
password VARCHAR(50)
);
INSERT INTO account(username, password)
VALUES
("bob", md5('password from bob')),
("jack", md5('password from jack')),
('joe', md5('password from joe'));
SQL FIDDLE DEMO
Sample page1
<?php
session_start();
$login = $_SESSION['login'];
$username = $_SESSION['username'];
echo '<h1>It WORKS, <i>'.$username.'</i>!!!</h1>';
?>
Important to note is that I have used the MYSQLI library instead of the MYSQL library. If you have more than one column in you table you should select your output per column. For example, $result['id'].
I found that you didn't escape variable in and out in you SQL statement. I have to note that I didn't debug the part below COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS. I think you can manage that on your own.
W.R.T. the santization and validation you have to do some more work. I don't know how you data is past via the user login in form. Let say you will use POST. In that case you can start at the top of you page with first retrieving all the posted variable using $_POST. Then filter them to make sure you code in is not open for SQL injection. E.g. $username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);