I'm kinda new to the OOP(? If this IS OOP, I don't know) language, and I'm trying to make a simple login-proccess, with MySQLi. The problem are, that the code doesn't work. I can't login (and It's not showing me any errors) and I can't register an new account (same problem) - It's like the code are dead or something.
I'm not sure I've done it right, but this is my best, so far. 'cause I'm new to OOP(?).
Index.php:
<?php
if(isset($_POST['submit'])) {
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string(md5($_POST['password']));
$userControl = "SELECT * FROM users WHERE username='".$username."' AND password='".$password."'";
$userControlResult = $mysqli->query($userControl);
if($mysqli->num_rows($userControlResult) > 1) {
$userRow = $mysqli->fetch_assoc($userControlResult);
$dbid = $userRow['id'];
$dbuser = $userRow['username'];
$_SESSION['id'] = $dbid;
$_SESSION['username'] = $dbuser;
header("location: me.php");
die();
} else {
echo "<div class='errorField'>Användarnamnet eller lösenordet är fel!</div>";
}
}
?>
I suppose that if I can solve the first error, I can solve the second too.
Thanks!
Many things I would recommend changing about your code:
Don't use mysql_real_escape_string() if you're using mysqli. You can't mix these APIs.
No need to escape a string returned by md5(), because it's guaranteed to contain only hexadecimal digits.
Don't use mysqli_real_escape_string() anyway -- use parameters instead.
Always check if prepare() or execute() return false; if they do, then report the errors and exit.
You can get a mysqli result from a prepared statement using mysqli_stmt_store_result().
Don't SELECT * if you don't need all the columns. In this case, you already have $username so all you really need to fetch is the id column.
No need to check the number of rows returned, just start a loop fetching the rows (if any). Since you exit inside the loop, your "else" error clause will be output only if the loop fetches zero rows.
Consider using a stronger password hashing function than MD5. Also, add a salt to the password before hashing. Read You're Probably Storing Passwords Incorrectly.
Example:
<?php
if(isset($_POST['submit'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
$userControl = "SELECT id FROM users WHERE username=? AND password=?";
if (($userControlStmt = $mysqli->prepare($userControl)) === false) {
trigger_error($mysqli->error, E_USER_ERROR);
die();
}
$userControlStmt->bind_param("ss", $username, $password);
if ($userControlStmt->execute() === false) {
trigger_error($userControlStmt->error, E_USER_ERROR);
die();
}
$userControlResult = $userControlStmt->store_result();
while($userRow = $userControlResult->fetch_assoc()) {
$_SESSION['userid'] = $userRow["id"];
$_SESSION['username'] = $username;
header("location: me.php");
die();
}
// this line will be reached only if the while loops over zero rows
echo "<div class='errorField'>Användarnamnet eller lösenordet är fel!</div>";
}
?>
A good command to enter at the top of the script (under the
ini_set('display_errors', 1);
This will display any errors on your script without needing to update the php.ini (in many cases). If you try this, and need more help, please post the error message here and I'll be able to help more.
Also, if you are using $_SESSION, you should have
session_start();
at the top of the script under the
Make sure your php is set to show errors in the php.ini file. You'll need to do some research on this on your own, but it's fairly easy to do. That way, you'll be able to see what the error is and go from there.
Related
This is my login php code but I am unable to login.
My code works until echo "2", after that is not working anymore.
include 'inc.config.php';
if(isset($_POST["submit"]))
{
$user = mysql_real_escape_string($_POST['emailid']);
$pass = md5(mysql_real_escape_string($_POST['password']));
$query=mysql_query("SELECT * FROM logsignup WHERE email='$user' AND password='$pass' ");
echo "1";
$numofrows = mysql_num_rows($query);
echo "2";
if($numofrows!=0)
{
echo "3";
while($row=mysql_fetch_assoc($query))
{
$dbusername= $row['emailid'];
$dbpassword= $row['password'];
}
if($user=$dbusername && $pass=$dbpassword)
{
echo "loggedin";
}
}
else
{
echo "invalid";
}
}
Here is inc.config.php file
$con = mysql_connect("localhost","root","");
$select=mysql_select_db("loginsignup");
Image of the database:
Update to MySQLi, as mysql_ is now deprecated. Read How do I migrate my site from mysql to mysqli? as a starter guide.
Stop using md5 as a password hashing function and instead use password_hash or a similar proven function.
if($user=$dbusername && $pass=$dbpassword) this is running the logic:
If value I get out of the database is the same as the value I put into the database.
Which is pretty pointless, it's a needlessly excessive check. It's better to count the correct number of rows returned, which will tell you exactly the same information.
You need to start using error logging, to help yourself solve your own errors, please read How to get useful error messages in PHP?
Also use MySQL EXPLAIN in (PHPMyAdmin) to help you understand wayward SQL queries.
Your password field in your screenshot looks far too short. md5 is typically 32 characters long, so what could be happening is that the SQL comparison is failing because you're comparing a long string with a shorter string. Double check.
Ensure you are using the correct Character encoding throughout your PHP and your MySQL, please read UTF-8 all the way through and convert all MySQL into utf8mb4_unicode_ci. Also get used to using PHP Multibyte string functions (may need installing).
If the above guides do not solve your problem you will at the very least have a clear path (with the error logs) to see what's going wrong and from that how to solve your issue.
<?php
`include 'inc.config.php';
if(isset($_POST["submit"]))
{
$user = mysql_real_escape_string($_POST['emailid']);
$pass = md5(mysql_real_escape_string($_POST['password']));
$sql="SELECT * FROM logsignup WHERE email='$user' AND password='$pass'";
$query=mysql_query($sql);
$numofrows = mysql_num_rows($query);
if($numofrows > 0)
{
$row=mysql_fetch_assoc($query)
$_SESSSION['EMAIL']= $row['emailid'];
$_SESSSION['USERNAME'] $row['username'];
if( $_SESSSION['EMAIL'] && $_SESSSION['EMAIL']) {
echo "valid";
}else{
echo "invalid";
}
}
}`
?>
Im having a problem of accessing the session variable value.
im creating a login page and this were i set the values of my session variables.
index.php
<?php
session_start();
$result=mysql_query("select * from myuser where id='".$id ."' and password='".$password."'");
if(mysql_num_rows($result) > 0){
$user = mysql_fetch_assoc($result);
$_SESSION['SESS_ID'] = $user['id'];
$_SESSION['SESS_UNAME'] = $user['username'];
$_SESSION['SESS_PASS'] = $user['password'];
header("location:home.php");
exit();
}
?>
home.php
<?php
session_start();
if(!isset($_SESSION['SESS_ID']) || (trim($_SESSION['SESS_ID'])) == ''){
header("location:index.php");
exit();
}
?>
<html>
<body>
<p>Login Successful</p>
<?php echo $_SESSION['SESS_ID'] ; ?>
</body>
</html>
the problem here is i have no value in $_SESSION['SESS_ID']..so how do i get or access the value of this session variable in my home.php?
Edit: my query for the SQL is
select * from myuser where id='".$id ."' and password='".$password."'
Some points about why you have this issue:
the values you populate the $_SESSION array with come directly from the database, but you have no database SQL query - instead you have
"!--query written here --"
If you can replace this placeholder with a query that returns your id, username and password values then your code should execute as expected.
I'm not certain if your syntax is wrong as such, but it is not the shape I would ever lay it out, my own shape would be:
$result = mysqli_query($connection, $sql);
while ($outputrow = mysqli_fetch_array($result)){
// In here $outputrow is an array of ONE row of your database, so
// $outputRow['id'] = the id from one row. ordered by the ORDER BY in your SQL query.
}
Add a mysqli_error($connection) clause to your SQL query to detect errors. such as :
Here:
$result=mysqli_query($connection, "<!--query written here -->") or die("error :".mysqli_error($connection));
As I have used across these examples, please, please STOP using MySQL and use at least MySQLi or even PDO. There are a host of improvements and bug fixes and lots of info on this transition on SO.
Also, never, ever compare passwords as strings, passwords saved to a database should as a minimum be saved as hashes with PHP function password_hash(). Never have the line if($_POST['pwd'] == $row['pwd']){.
Finally, as rightly mentioned by Fred-ii- in comments, add error logging and checking into your script so that you know what's going on:
Such as:
error_reporting(E_ALL);
ini_set('display_errors', 1);
Add these to the very top of your PHP page and they will display your errors and warnings to you so you can see what is and is not working.
EDIT:
From your edit there are two biq questions, your statement is that:
"select * from myuser where id='".$id ."' and password='".$password."'
so where does the value $id and $password come from? is the <?php at the top of the page, if so, these variables will always be empty, you need to apply a value to these variables.
I hope I formatted the code properly. I am having trouble making this if statement to work. I've searched and from what it looks like this statement should work. However, when I run it no matter the password if the username starts with kacey then it goes to echo "Logged in as: " . kacey;
Likewise, if I put the input to kaceyfeewaf, it still goes to echo "Logged in as: " . $myuser; This happens regardless of the password I put in. the line $result['username'] should validate to KACEY.
$sql = "SELECT * FROM $dbTable WHERE username = $myuser AND password = $mypass";
$result = mysql_query($sql);
if($result['username'] = $myuser && $result['password'] = $mypass;)
{
echo "Logged in as: " . $myuser;
} else {
echo "Fail ";
}
There are a few issues here.
Firstly, the variables you have in your query are strings, therefore they require to be quoted:
WHERE username = '$myuser' AND password = '$mypass'
Having or die(mysql_error()) to mysql_query() would have signaled the syntax error.
Then you're assigning instead of comparing with
if($result['username'] = $myuser && $result['password'] = $mypass;)
use two equals ==
However, that isn't how you check if those rows exist.
You need to use mysql_num_rows() or use a while loop while using a function to fetch/iterate over results found.
Here is an MySQLi example using mysqli_num_rows():
$conn=mysqli_connect("hostname","username","password","db");
$check_select = mysqli_query($conn, "SELECT * FROM `users`
WHERE email = '$email' AND pw='$pass'");
$numrows=mysqli_num_rows($check_select);
if($numrows > 0){
// do something
}
Now, we don't know where those variables have been assigned, and if from a form that it's using a POST method with matching name attributes.
I.e.:
<form action="" method="post">
<input type="text" name="username">
...
</form>
$username = $_POST['username'];
Another thing which is unknown to us is the MySQL API you're using to connect with. Make sure that you are indeed using the same one as you are using to query with, being mysql_. Different APIs do not intermix, such as mysqli_ or PDO. Use the same one from connection to querying.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
I recommend you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
Here is a PDO solution pulled from one of ircmaxell's answers:
https://stackoverflow.com/a/29778421/
Just use a library. Seriously. They exist for a reason.
PHP 5.5+: use password_hash()
PHP 5.3.7+: use password-compat (a compatibility pack for above)
All others: use phpass
Don't do it yourself. If you're creating your own salt, YOU'RE DOING IT WRONG. You should be using a library that handles that for you.
$dbh = new PDO(...);
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?");
$stmt->execute([$username, $email, $hash]);
And on login:
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute([$_POST['username']]);
$users = $result->fetchAll();
if (isset($users[0]) {
if (password_verify($_POST['password'], $users[0]->password) {
// valid login
} else {
// invalid password
}
} else {
// invalid username
}
You should use == instead of simple = for your if condition
First of all delete that if stmt and make new one where you check for num rows. If there is num rows > 0 you have valid login. And then print needed results from database od current query.
Edit:
You have = insted of == or === so stmt is always true.
Before you say it: I know the passwords should be encrypted/hashed, but I want to get this down first:
I have this login function and a SQL database. However, the login function doesn't seem to work and I haven't the faintest idea why. I am probably missing something stupid, but have been struggling with this for a while now. Any help would be appreciated!
NOTE: the file db_connect.php is really just a basic connecting to the database, nothing wrong there
FUNCTION.PHP:
<?
function login($username, $password, $con)
{
$myQuery = "SELECT * FROM Members WHERE Username = '$username' and Password = '$password';";
$result = mysqli_query($con, $myQuery);
if (mysql_num_rows($result) == 0)
{
return false;
}
else
{
return true;
}
}
?>
PROCESS-LOGIN.PHP:
<?php
include 'db_connect.php';
include 'functions.php';
if (isset($_POST['username'], $_POST['pword'])) {
$username = $_POST['username'];
$password = $_POST['pword']; // The hashed password.
if (login($username, $password) == true) {
// Login success
header('Location: welcome.html');
}
else
{
// Login failed
header('Location: index.html');
}
}
else {
// The correct POST variables were not sent to this page.
echo 'Invalid Request';
}
?>
You are not providing the $con parameter to login function.
function login($username, $password, $con)
You are calling it as
login($username, $password)
Try providing the connection argument to see if it works.
Also note the answer kingkero made. You are using functions from different libraries.
Some things I noticed
Are you using method="POST" in your form?
Your SQL query is vulnerable to SQL injections
your mixing mysql_* with mysqli_* functions
missing $con parameter for login function
You are mixing MySQLi (mysqli_query) with MySQL (mysql_num_rows) - decide for either one (preferably the former).
If you are using MySQL, the parameters for mysql_query are in wrong order.
In addition to that you are failing to pass the connection to the login as a parameter (as WoLfulus mentioned).
Some additional info as you seem to be learning:
The return statement of login can be simplified to return mysql_num_rows($result) == 1;. This will return TRUE if one record was found and FALSE otherwise - no need for an if/else statement here, you already have the logic you need.
Right now anyone can access welcome.html without logging in by simply typing the address in the browser. This can be avoided by using sessions.
Since you don't properly escape the user input (which one should never trust!), you are vulnerable to SQL injections. mysql_real_escape_string is a start but no 100% solution. If you used prepared statements on the other hand, you wouldn't need to worry.
I'm answering since I don't have enough reputation to comment your question.. But you should keep your variables outside the quotes and add mysql_real_escape_string() to prevent mysql injection..
$myQuery = "SELECT * FROM Members WHERE Username = '$username' and Password = '$password';";
Should be:
$myQuery = "SELECT * FROM Members WHERE Username = '". mysql_real_escape_string($username) ."' and Password = '". mysql_real_escape_string($password) ."';";
please help i have the following php code for my login session but i am trying to get the $_session['user_id'] instead of the $_session['email']. i tried print_f function to see what i can use but user_id array says 0 which cannot be right unless i read it wrong.
session_start();
$email = strip_tags($_POST['login']);
$pass = strip_tags($_POST['password']);
if ($email&&$password) {
$connect = mysql_connect("xammp","root"," ") or die (" ");
mysql_select_db("dbrun") or die ("db not found");
$query = mysql_query("SELECT email,pass FROM members WHERE login='$email'");
$numrows = mysql_num_rows($query);
if ($numrows!=0) {
// login code password check
while ($row = mysql_fetch_assoc($query)) {
$dbemail = $row['login'];
$dbpass = $row['password'];
}
// check to see if they match!
if ($login==$dbemail&&$password==$dbpass) {
echo "welcome <a href='member.php'>click to enter</a>";
$_SESSION['login']=$email;
} else {
echo (login_fail.php);
}
} else {
die ("user don't exist!");
}
//use if needed ==> echo $numrows;
} else {
die ("Please enter a valid login");
}
i am trying to get the $_session['user_id'] instead how can get this to use instead of $_session['email']. tried using $_session['user_id'] but instead i got undefined error msg.
Well, you don't define $_session['user_id'] anywhere in this script, so it's no surprise that it's not defined. You have to assign it a value before you can refer to it.
Also, note that there all kinds of security problems with this code.
You're running your MySQL connection as the root user. This is NOT a good idea.
You're trusting user input, which opens your script up to a SQL injection attack. Stripping HTML tags from the user input does not make it safe. Suppose that I came to your site, and filled in the "email" field with this:
bob#example.com'; GRANT ALL PRIVILEGES ON *.* TO 'evil_bob' IDENTIFIED BY '0wned_joo';
As currently written, your script would happily run its query as normal, and also create an account called "evil_bob" with full privileges to all the information in all of the databases on your server.
To avoid this, NEVER assume that user input is safe. Validate it. And to be extra sure, don't stick variables straight into SQL you've written. Use bound parameters instead. There are a few cases where it's hard to avoid -- for example, if you need to specify the name of a column rather than a piece of data, a bound parameter will not help and you'll have to do it some other way. However, for any piece of data you're using as part of a query, bind it.