I am new to PHP / MySql programming. I have purchased a book to help learn the language and I have done well so far except when I tried to create an authentication system.
I want to be able to match the record to the database using MD5 encryption and if found send to the website. If the username and password are incorrect then send them to the login page again.
At one point it would only match the first record. Now it won't match any. I can type exactly what is in the database and the result still goes to 0 or back to the login page.
Also I am wanting to set a session variable for the username and auth_level so that I can call on it throughout my website/application.
I am using XAMPP on Mac if that helps.
Auth Script:
if ((!isset($_POST['username'])) || (!isset($_POST['password']))) {
header('Location: login.html');
exit;
}
$mysqli = mysqli_connect('localhost', 'username', 'password', 'testDB')
or die(mysql_error($mysqli));
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$password = mysqli_real_escape_string($mysqli, $_POST['password']);
$auth_sql ="SELECT username , auth_level FROM auth_users WHERE
username ='".$username."' AND password =MD5('".$password."')";
$auth_sql_res = mysqli_query($mysqli, $auth_sql) or die(mysqli_error($mysqli));
if (mysqli_num_rows($auth_sql_res) == 1) {
$_SESSION['username'] = $username;
header('Location: homebeta.php');
} else {
header("Location:index.php");
exit;
}
PHP v5.3.1
Thank you everyone that takes the time to look, analyze, and/or help. I really appreciate your time.
You forgot an exit after the first call to header:
header('Location: homebeta.php');
exit;
Are you checking PHP errors? Read How to get useful error messages in PHP? to know more.
I think your script may output something at the beginning, that prevents headers or session information to be sent.
Try this:
if ((!isset($_POST['username'])) || (!isset($_POST['password']))) {
header('Location: http://www.replacethis.com/login.html');
} else {
$mysqli = mysqli_connect('localhost', 'username', 'password', 'testDB')
or die(mysql_error($mysqli));
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$password = mysqli_real_escape_string($mysqli, $_POST['password']);
$auth_sql = "SELECT `username`, `auth_level`
FROM `auth_users`
WHERE `username` = '$username' AND `password` = MD5('$password')";
$auth_sql_res = mysqli_query($mysqli, $auth_sql)
or die(mysqli_error($mysqli));
if (mysqli_num_rows($auth_sql_res) > 0) {
$_SESSION['username'] = $username;
header('Location: http://www.replacethis.com/homebeta.php');
} else {
header("Location: http://www.replacethis.com/index.php");
exit;
}
}
Else statement added.
Backticks in your SQL query (Just to be on the safe side)
Absolute URL in the header location.
And try removing the MD5 hashing from your query and copy n paste both username AND password in your HTML-form and then login.
Well, you may not getting your error messages, since you are using mysql_error instead of mysqli like everything else, and specifically on connect, there is mysqli_connect_error().
Also, according to the manual, inside the parentheses should be void for mysqli_connect_error:
$mysqli = mysqli_connect('localhost', 'username', 'password', 'testDB')
or die(mysqli_connect_error());
Related
<?php
session_start();
include("connection.php");
if (mysqli_connect_error()) {
die("Could not connect to database");
if ($_POST['submit'] == "Login") {
$query = "SELECT * FROM EmployeeTable WHERE name='"
. mysqli_real_escape_string($link, $_POST['name'])
. "'AND password='"
. md5(md5($_POST['name']) . $_POST['password'])
. "'LIMIT 1";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
if ($row) {
$_SESSION['id'] = $row['id'];
header("Location: http://www.ccm.net/forum/");
} else {
$error = "We could not find a user with that email and password. Please try again.";
}
}
?>
I have the above codes just to login an user.I have a table with the username and password already.I dont want to create a signup button,just a login button as the password will be their 'id' itself.I am able to connect to db.
Please help me, as after login I'm taken to a blank page.
First off all: You are vulnerable to sql injections using this code. Please use parametrized queries so you don't forget to escape values you use in your queries.
$mysqli = new Mysqli($host, $username, $password, $database);
$mysqli->prepare('SELECT * FROM EmployeeTable WHERE name = ? AND password = ? LIMIT 1');
$mysqli->bind_param('ss', $name, $password);
$mysqli->execute();
$result = $mysqli->fetch_array();
You should also not use md5 for password hashing. Use the built in password_* functions.
password_hash can be used to hash passwords like so:
$hash = password_hash($password, PASSWORD_DEFAULT);
This also applies what is called a salt to strengthen the hash against dictionary attacks.
When you want to verify passwords use can use password_verify to verify the password against the stored hash like so:
$is_correct = password_verify($password, $hash);
Using these methods you are very unlikely to mess anything up.
A direct answer to your question could be either: if ($_POST['submit'] == "Login") or if($row). I would use count() to check the number of results found like so: if(count($row) > 0).
At a guess without seeing the rest of the HTML, it is probably not satisfying the if $_POST["submit"] statement:
if ($_POST['submit'] == "Login") {
and just ends the script as there is no else option. Perhaps check that your form is POST, Name of button is actually "submit" and its value is "Login"
when I submit this form i have the same error message all the time . even if i put right or wrong password or don't put password or i write the name of the data base wrong . all of this wrongs i have the same error message :
Please enter a username and password .
so what is the problem . and i am sure about my fields on data base .
<?
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if ($username && $password)
{
$connect = mysql_connect("localhsost","root","adminffpass") or die("Couldent connet to database ");
mysql_select_db("login") or die("No data base found ");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if ($numrows !=0)
{
while ($row= mysql_fetch_array($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if ($username == $dbusername && $password==$dbpassword)
{
echo "Login successul .<a href='memeberarea.php'>Click to enter member area</a>";
$_SESSION['username'] = $dbusername;
}
else
echo "incorrect password ";
}
else
die ("That user name dosent exist");
}
else
die ("Please enter a username and password");
?>
Even if i put right or wrong password or don't put password or i write the name of the data base wrong . all of this wrongs i have the same error message
Typo: localhsost for one thing. Plus, you may not be able to use mysql_ functions, since they are deprecated and may not be available for you to use.
Plus, your POST arrays may be failing, so make sure your form is a POST method and that your elements bear the name attribute.
I.e.:
<input type="text" name="username">
etc.
if i write wrong name database i don't have any error . why ?"
Because, you're just using or die("Couldent connet to database ") instead of getting the real error mysql_error()
mysql_connect() => http://php.net/manual/en/function.mysql-connect.php
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
For password storage, use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
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: Error reporting should only be done in staging, and never production.
Plus, instead of if ($username && $password) you should be using a conditional !empty() for your inputs.
It is also best to use proper and consistent bracing throughout your code.
else{
echo "incorrect password ";
}
etc.
Not doing so, could have adverse effects.
Storing a password hash
Using PDO with prepared statements and password_hash():
Pulled from ircmaxell's answer: 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 may print some information for yourself, so you could see, what's wrong. Change the following line:
echo "incorrect password ";
to something like this:
echo "incorrect password, u:[$username/$dbusername] p:[$password/$dbpassword]";
If you will see that detailed message, you will know, what's wrong.
EDIT: of course, don't left pwd printing in your final code :)
I'm relatively new to php, and I'm trying to write a really simple login script. I've got the basic functionality down, but I can't login to the system. My login script is below, and my registration script is below as well.
checklogin.php
include_once 'inc/db.inc.php';
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string(md5($_POST['password']));
try {
$sql="SELECT id, username, password FROM users WHERE username='$username' and password='$password'";
$result = $pdo->query($sql);
$count=mysql_num_rows($result);
// If result matched $username and $password, table row must be 1 row
if($count == 1){
// Register $username, $password and redirect to file "index.php"
session_register("username");
session_register("password");
header("Location: index.php");
}
else {
header("Location: login.php?invalid=1");
}
}
catch (PDOException $e) {
echo $e;
}
ob_end_flush();
?>
checkreg.php
include_once 'inc/db.inc.php';
//This makes sure they did not leave any fields blank
if (!$_POST['username'] | !$_POST['password'] | !$_POST['passwordconf'] ) {
die('You did not complete all of the required fields');
}
if ($_POST['password'] != $_POST['passwordconf']) {
die('Your passwords did not match. ');
}
$_POST['password'] = md5($_POST['password']);
if (!get_magic_quotes_gpc()) {
$_POST['password'] = addslashes($_POST['password']);
$_POST['username'] = addslashes($_POST['username']);
}
$username = $_POST['username'];
$password = $_POST['password'];
try {
// now we insert it into the database
$sql = "INSERT INTO users(username,password) VALUES ('$username','$password')";
$result = $pdo->exec($sql);
header("Location: index.php");
} catch (PDOException $e){
echo $e;
}
?>
I know that the registration is writing to the database, but everytime I attempt a valid login I receive my invalid credentials flag. Anything you can do to help me would be awesome. Thank you.
Your issue could be with session_register(), depending on the version of PHP you're using. Try putting
session_start();
At the top of checklogin.php, then using
...
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
...
instead of session_register().
First you should clear some things out:
1.
if (!$_POST['username'] | !$_POST['password'] | !$_POST['passwordconf'] ) {
die('You did not complete all of the required fields');}
it should be && and not |.
In your code there's nowhere to check if username exists or not, so i'm guessing that you have multiple users with the same username. Before inserting in your checkreg.php, you should fist check if the username exists or not.
in your checklogin.php change if($count == 1) to if($count > 0)
If this not helped could you give me more information like database data (the data that is in your database now)
<?php
// Use of session_register() is deprecated
$barney = "A big purple dinosaur.";
session_register("barney");
// Use of $_SESSION is preferred, as of PHP 4.1.0
$_SESSION["zim"] = "An invader from another planet.";
// The old way was to use $HTTP_SESSION_VARS
$HTTP_SESSION_VARS["spongebob"] = "He's got square pants.";
?>
Warning:
This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
Couple of things to try:
1) The session_register function call is deprecated. http://php.net/manual/en/function.session-register.php. You really ought to be using $_SESSION if at possible.
Something like this:
$_SESSION["username"] = $username;
$_SESSION["password"] = "validated"; // md5 is variable so you can't easily check for it on next page render
2) When testing for the values, you don't want $_POST, you want to use $_SESSION again on the next page render. Something like this:
if ("validated" == $_SESSION["password"]) {
// You're logged in...
}
3) Note, for the $_SESSION array to be populated you must call session_start(); once and only once before use. (http://www.php.net/manual/en/function.session-start.php for more.)
4) I know this is sample code, but SQL Injection attack possible. Need to escape those variables.
$sql="SELECT id, username, password FROM users WHERE username='$username' and password='$password'";
Alright, so I'm building a new app, and have decided to use PDO for database access. (I'm completely new to PDO, but am under the impression that it is the best way to go about db access).
Right now, my login script is incredibly simple. It checks the database for a user with the given username (from the login form), attempts to match the given password with the stored one in plain text (no encrypting/decrypting yet), and redirect the user as necessary. Here is a simple sequence diagram:
Login Screen ---(user enters credentials)--->Login Handler---(gets user details and compares pw)-->if (pw == stored pw)--->dashboard / else --->login w/ error msg
Sorry if that's hard to read, I wasn't sure the best way to represent the flow...anyways...
Here's my issue: I input the correct username and password (case sensitive even!), and am always redirected back to the login screen with the error message. However, if I simply go to the dashboard via the url bar, I am not redirected back to the login screen (as I should be if no session is set), and my username is displayed in the navigation bar (as if I had logged in correctly).
Again, sorry if this is hard to follow. Its sort of difficult to simply explain. If this is an issue, I can perhaps do a screencast of sorts to explain better. Either way, here is my code:
loginHandler.php
if(!isset($_POST['username']) || !isset($_POST['password'])){
header('Location: login.php?error=pass');
}
$username = $_POST['username'];
$pass = $_POST['password'];
//TODO: crypt password
try{
$DB = new PDO("mysql:host=127.0.0.1;port=8889;dbname=cTix", 'root', 'root'); //TODO: change this when uploading to webserver
$STH = $DB->prepare("SELECT * FROM users WHERE username = $username LIMIT 0, 1");
$STH->setFetchMode(PDO::FETCH_OBJ);
$STH->execute();
$u = $STH->fetch();
if($pass == $u->password){
session_start();
$_SESSION['uid'] = $u->id; //TODO: securely store uid
header('Location: index.php');
} else {
//echo 'Your Password: ' . $pass . ' - Correct Password: ' . $u->password;
header('Location: login.php?error=pass');
}
} catch(PDOException $e){
//echo $e->getMessage();
header('Location: login.php?error=true');
exit;
}
here is code that is retrieving the username for dashboard.php:
function connection(){
$host = 'localhost';
$dbname = 'cTix';
$user = 'root';
$pass = 'root';
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
return $DBH;
} catch(PDOException $e){
echo $e->getMessage();
return null;
}
}
function getUserById($id){
$DB = connection();
$STH = $DB->query("SELECT * FROM users WHERE id = $id");
$STH->setFetchMode(PDO::FETCH_OBJ);
$u = $STH->fetch();
$DB = null;
return $u;
}
function getUserName(){
echo getUserById(getCurrentUserId())->name;
}
If there is any other information I can offer, or anything I can provide that would be more helpful, please let me know!
Unfortunately, without this stupid login issue figured out, I can't make any headway on this app, so any help would be greatly appreciated! Thanks SO!
Here's where your problem is:
$STH = $DB->prepare("SELECT * FROM users WHERE username = $username LIMIT 0, 1");
You're concatenating the username into your SQL string, but not quoting it out. I suspect that this will fix the problem:
$STH = $DB->prepare("SELECT * FROM users WHERE username = '$username' LIMIT 0, 1");
HOWEVER
You should look into how to use bound parameters. You're already using PDO, but you're still writing user-entered code in your SQL, and bound parameters avoid that - it would also have avoided this problem, too.
This ought to work, but I've not tested it:
$STH = $DB->prepare('SELECT * FROM users WHERE username = ? LIMIT 0, 1');
$STH->bindParam(1, $username);
$STH->setFetchMode(PDO::FETCH_OBJ);
$STH->execute();
I tried to do use cookies to remember login information but the cookies never seemed to "take" as it were. Here's the initial login script:
//try to login using cookies, but first make sure it doesn't have a $_SESSION variable for it
if (!(isset($_SESSION['valid_user']))) {
if (isset($_COOKIE["login"])) {
//try to login using cookie
$query = "select from cookie_users where uniqueid = '".$_COOKIE["login"]."')";
$conn = new mysqli('localhost', 'user', 'password', 'test');
$result = $conn->query($query);
if ($result->num_rows>0) {
$result->fetch_assoc();
$result['username'] = $username;
$result['password'] = $password;
//try to login using password and username from cookie database
$query = "select * from authorized_users where username = '".$username."' and password = '".$password."'";
$result2 = $conn->query($query);
if ($result->num_rows>0) {
$_SESSION['valid_user'] = $username;
}
}
}
}
if (isset($_POST['userid']) && isset($_POST['password'])) {
// if the user has just tried to log in
$userid = $_POST['userid'];
$password = $_POST['password'];
$db_conn=new mysqli('localhost', 'user', 'password', 'test');
if (mysqli_connect_errno()) {
echo 'Connection to database failed: '.mysqli_connect_errno();
exit;
}
$query = 'select * from authorized_users '."where name='$userid' "."and password=sha1('$password')";
$result = $db_conn->query($query);
if ($result->num_rows > 0) {
//if they are in the database, register the user id
$_SESSION['valid_user'] = $userid;
//set up cookie
setcookie("login", $uniqueid, time()*60*60*24*14);
$query = "insert into cookie_users values ('".$userid."', sha1('".$password."'), '".$uniqueid."')";
$result = $db_conn->query($query);
if (!$result) {
echo 'Could not update cookie in database';
}
}
$db_conn->close();
}
Members only content:
if (isset($_SESSION['valid_user'] {
echo "members only content goes here";
} else {
echo "you need to login"; }
The sessions and login scripts work just fine. If they login directly using the login page, it shows up. If they go to another page and then come back, it still works; so that leaves me to believe that the sessions work just fine. However, if you close down the browser and come back, it doesn't register. If something's messed up with the script, please let me know. Either way, I did a test script and not even that works. Here it is:
<?php
setcookie("test", "the test is good", time()*60*60);
?>
<html>
<body>
<?php
echo $_COOKIE["test"];
?>
</body>
</html>
So I think I'm missing something fundamental. Sorry if the answer is painfully obvious, cookies are new to me. Thanks for any help you guys can give.
Your problem is in this line:
setcookie("login", $uniqueid, time()*60*60*24*14);
Here, you're multiplying the time instead of adding to it. You've multiplied it by enough to exceed the MAX_INT size (see Y2038). For whatever reason, Apache (at least, on my system) will ignore that header and the browser will then keep it only for the length of the session. Fortunately, you can fix the problem fairly simply:
setcookie("login", $uniqueid, time() + 60*60*24*14); // Adding two weeks, not multipying by >9000