/    Sign up×
Community /Pin to ProfileBookmark

Login page using php?

i am trying to make a login page for my website using msql and phpmyadmin can someone pleaswe help me with the connection codeP.S i am not using localhost i am using a web server: host gator…

to post a comment
PHP

8 Comments(s)

Copy linkTweet thisAlerts:
@Sup3rkirbyOct 23.2014 — There's actually a lot involved in a (decent) login system. So I can't just spout out a few lines for you and solve all your problems, but I can guide you to the steps you need to take to make such a thing work.

Firstly, you'll actually need to create a database and then a table within this database to hold user information. The fields you have in this table are up to you, but ideally you'll have at least an [B][I]id[/I][/B], [B][I]username[/I][/B] and [B][I]password[/I][/B] field. The [B][I]id[/I][/B] field would be an [I]auto-incrementing integer[/I] (there's a checkbox for auto-increment in phpMyAdmin) and the [B][I]username[/I][/B] and [B][I]password[/I][/B] fields would be a [I]varchar[/I] type (with something like a 16-32 character limit on the [I]username[/I] and a 64-128 character limit on your [I]password[/I] field).

Next you'll actually need a user in the database table to login with. I suppose you could manually add a record, though you'll need to make sure you handle your password field properly. All passwords should be hashed in some way. phpMyAdmin will automatically hash values with md5 or sha1, but realistically you'll want to shy away from that and use something a little more secure, which means you can't add a user via phpMyAdmin. For my examples I'll be using sha256 for which you can find a number of online tools that will generate the hash for you if you want to manually add a record to your database.

So let's say you added a user to the database and actually have a hashed password in the password field... You'll want to have a script that can log you in. Below I have a simple PHP script that gets a username and password from a form and then would check it against a database to see if the info is valid.
[code=php]
<?php
$db_name = "YOUR_DATABASE_NAME";
$db_user = "YOUR_DATABSE_USERNAME";
$db_password = "YOUR_DATABSE_PASSWORD";
$db_table = "YOUR_DATABSE_TABLE";
function getDB() {
try {
$dbho = new PDO('mysql:host=localhost;dbname='.$db_name, $db_user, $db_password);
$dbho->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
exit("Failed to connect to the database! Better contact support and yell until this is fixed.");
break;
}
return $dbho;
}

$user = (isset($_POST['username'])) ? $_POST['username'] : "";
$pass = (isset($_POST['password'])) ? $_POST['password'] : "";

if($user != "" && $pass != "") {
$dbho = getDB();

$data = array("username"=>$user);
$stmt = $dbho->prepare("SELECT username, password FROM " . $db_table . " WHERE username = :username");
$stmt->execute($data);

if($stmt->rowCount() > 0) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if($row['password'] == hash('sha256', $pass)) {
echo "You have been successfully logged in!";
// Additional login code would go here, either to set cookies or session data
break;
} else {
echo "It looks like the password you entered was incorrect. Double-check everything and try again or try resetting your password.";
break;
}
}
} else {
echo "We couldn't find the user '" . $user . "' anywhere in the database. Make sure you entered everything correctly and try again.";
}
} else {
echo "The username or password entered was empty!";
}
?>
[/code]


With the script above you'd need to enter in the name of your database, your database username and password, as well as the name of the table you created. These values all go into the variables located at the top of the script. For reference, the user and password you use to log into your hostgator account are also your 'root' user for the database, thus you can use that same user and password for this.

And just a side note, if this page/site is running on the same server as your database then yes you would be using localhost. localhost is just an alias for the current server and serves as an easy shortcut rather than typing in an IP or hostname.
Copy linkTweet thisAlerts:
@yahooiseeuauthorOct 24.2014 — have a problem when ever i try to login either with password no username username no password incorrect username and password etc. etc. it just refreshes the page heres what i got now that you have helped me superkirby :[code=php][code=html]<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>sign up</title> <link rel="stylesheet" href="css/style.css" type="text/css"> </head> <body> <div id="header"> <div> </a> <ul> <li> <a href="index.html">Home</a> </li> <li class="selected"> <a href="signup.html">Sign Up</a> </li> <li> <a href="files.html">Files</a> </li> <li> <a href="about.html">About</a> </li> <li> <a href="contact.html">Contact</a> </li> </ul> </div> </div> <div id="body" class="home"> <div class="blog"> <div> </div> </div> <div class="article"> <div> <form action = "login.php" method="POST"> USERNAME: <input type="text" name="username"> PASSWORD: <input type="password" name="password"> <input type="submit"> </form> </div> </div> <div class="news"> <div> </div> </div> </div> <div id="footer"> <div> <div class="connect"> </div> </div> </div> </body> </html>[/code]
[code=php]<?php
$db_name = "*****";
$db_user = "*****";
$db_password = "*****";
$db_table = "members";
function getDB() {
try {
$dbho = new PDO('mysql:host=localhost;austen_login='.$db_name, $db_user, $db_password);
$dbho->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
exit("Failed to connect to the database! Better contact support and yell until this is fixed.");
break;
}
return $dbho;
}

$user = (isset($_POST['username'])) ? $_POST['username'] : "";
$pass = (isset($_POST['password'])) ? $_POST['password'] : "";

if($user != "" && $pass != "") {
$dbho = getDB();

$data = array("username"=>$user);
$stmt = $dbho->prepare("SELECT username, password FROM " . $db_table . " WHERE username = :username");
$stmt->execute($data);

if($stmt->rowCount() > 0) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if($row['password'] == hash('sha256', $pass)) {
echo "You have been successfully logged in!";
// Additional login code would go here, either to set cookies or session data
break;
} else {
echo "It looks like the password you entered was incorrect. Double-check everything and try again or try resetting your password.";
break;
}
}
} else {
echo "We couldn't find the user '" . $user . "' anywhere in the database. Make sure you entered everything correctly and try again.";
}
} else {
echo "The username or password entered was empty!";
}
?>[/code]
Copy linkTweet thisAlerts:
@yahooiseeuauthorOct 24.2014 — geuss i shouldn't have gave out my database credentials... woops
Copy linkTweet thisAlerts:
@Sup3rkirbyOct 27.2014 — That seems odd considering there is nothing in the PHP script that would take them back to the login page. Maybe I'm missing something obvious but your HTML form seems like it would have no trouble submitting to the PHP script and at this point you would end up with a white page that contained one of the messages from the script.

It's possible there's an error, though that hasn't ever been known to 'refresh' the page back to the previous page, so I can't see that being the problem.

What area the names of your files by chance? If the HTML you provided is in a file named 'login.php' then this would explain it since that page submits the data to itself (and obviously does nothing with it). You could combine the two so that it processes the form when submitted, and displays the login page otherwise, but for simplicity I'd say just make sure your HTML file is called 'login.html' and the PHP script is called 'login.php'. If everything starts working then I could help you combine the two files into one.
Copy linkTweet thisAlerts:
@deathshadowOct 27.2014 — 1) Might help if you didn't whitespace strip the **** out of your markup to at least tell what the devil that mess is doing.

2) Might help if it wasn't so heavy on "DIV for nothing" -- though that's hard to say for sure without seeing the full site with actual content.

3) Might help if you used a COMPLETE accessible properly written form -- as in "where are your fieldsets and labels?"

4) "post" should be lower case in the markup.

5) you don't need to say "break" after an "exit"

6) you probably shouldn't have more than one user with the same username, so there's no need to "while" the result.

7) It's bad practice to recover the password from the query. Send the sha256 of the pass IN the query for comparison instead, so all password access is mono-directional.

8) It's generally sloppy/insecure to put connection info into variables unless you're going to delete them right away. It's also not a great idea to put things like table names into variables, since one of the ENTIRE reasons to use PDO or mysqli instead of mysql is to NOT be blindly adding values in queries together.

9) I'm pretty sure "austen_login" is gibberish in a DSN, did you mean 'dbname'?

10) I probably also wouldn't be putting a function in global scope that created a DB context.

11) you didn't actually define $dbname (I'm going to use austen_login as the dbname for now)

First let's drag your markup kicking and screaming into the light.
&lt;form action="login.php" method="post" id="loginForm"&gt;
&lt;fieldset&gt;
&lt;label for="loginUser"&gt;USERNAME:&lt;/label&gt;
&lt;input type="text" name="username" id="loginUser" /&gt;
&lt;label for="loginPass"&gt;PASSWORD:&lt;/label&gt;
&lt;input type="password" name="password" id="loginPass" /&gt;
&lt;/fieldset&gt;
&lt;div class="submitsAndHiddens"&gt;
&lt;input type="submit" value="Login" /&gt;
&lt;input type="hidden" name="fromForm" value="loginForm" /&gt;
&lt;/div&gt;
&lt;/form&gt;


Then let's fix up that PHP.

login.php:
&lt;?php

$errors = [];

if (isset($_POST['fromForm']) &amp;&amp; ($_POST['fromForm'] == 'userLogin')) {

<i> </i>if (isset($_POST['username']) &amp;&amp; (isset($_POST['password'])) {
<i> </i> try {
<i> </i> $db = new PDO(
<i> </i> 'mysql:host=localhost;dbname=austen_login',
<i> </i> '', // user
<i> </i> '' // pass
<i> </i> );
<i> </i> } catch (PDOException $e) {
<i> </i> exit('Fatal Error, failed to connect to database.');
<i> </i> }

<i> </i> $stmt = $db-&gt;prepare('
<i> </i> SELECT id, username
<i> </i> FROM members
<i> </i> WHERE username = :username
<i> </i> AND password = :password
<i> </i> ');
<i> </i> $stmt-&gt;execute([
<i> </i> ':username' =&gt; $_POST['username'],
<i> </i> ':password' =&gt; hash('sha256', $_POST['password'])
<i> </i> ]);

<i> </i> if ($user =&gt; $stmt-&gt;fetch(PDO::FETCH_ASSOC)) {
<i> </i> echo 'You have been successfully logged in!';
<i> </i> } else {
<i> </i> $errors[] = 'Unknown user or invalid password, please try again.';
<i> </i> }
<i> </i>} else $errors[] = 'You failed to enter either a user name or password';

<i> </i>if (count($errors)) include('loginForm.php');

} else include('loginForm.php')

?&gt;


Though I'd put that form into a loginform.php thus:

&lt;?php

echo '
&lt;form action="login.php" method="post" id="login"&gt;';

if (isset($errors) &amp;&amp; count($errors)) {
echo '

<i> </i> &lt;ul class="errorList"&gt;';
<i> </i>foreach ($errors as $message) echo '
<i> </i> &lt;li&gt;', $message, '&lt;/li&gt;';
<i> </i>echo '
<i> </i> &lt;/ul&gt;';
}

echo '

<i> </i> &lt;fieldset&gt;
<i> </i> &lt;label for="loginUser"&gt;USERNAME:&lt;/label&gt;
<i> </i> &lt;input type="text" name="username" id="loginUser" ', (
<i> </i> isset($_POST['username']) ?
<i> </i> 'value="' . htmlspecialchars($_POST['username']) . '" ' :
<i> </i> ''
<i> </i> ), '/&gt;
<i> </i> &lt;label for="loginPass"&gt;PASSWORD:&lt;/label&gt;
<i> </i> &lt;input type="password" name="password" id="loginPass" /&gt;
<i> </i> &lt;/fieldset&gt;

<i> </i> &lt;div class="submitsAndHiddens"&gt;
<i> </i> &lt;input type="submit" value="Login" /&gt;
<i> </i> &lt;input type="hidden" name="fromForm" value="login" /&gt;
<i> </i> &lt;/div&gt;

<i> </i>&lt;/form&gt;';

?&gt;


Hope this helps -- there's still a LOT I'd do there to secure it further, like destroying the DB connection or getting it out of global scope by putting all that in a function or object. Oh, also this code is PHP 5.4/newer only. I've dropped saying "Array" every five seconds since if it can't run on 5.3/earlier, that's probably a GOOD THING since 5.3 is end of life and we're a year deep into 5.5 being latest mainstream.
Copy linkTweet thisAlerts:
@Strider64Oct 27.2014 — I would consider using password_hash, if you have 5.5 then it comes with it. Otherwise you can download it here: https://github.com/ircmaxell/password_compat

Which is good for PHP 5.3x and up

Info on how to use it -> http://php.net/manual/en/function.password-hash.php and http://php.net/manual/en/function.password-verify.php


The using it is as simple as :
[code=php]
// Hash the password - See above for details:

$password = password_hash($password, PASSWORD_BCRYPT, array("cost" => 15));



// Store user's credentials, if form data is validated:

if ($displayStatus == 'undetermined') {

// Using prepared statements:

$query = 'INSERT INTO users ( username, password ) VALUES ( :username, :password )';

$stmt = $pdo->prepare($query);

$result = $stmt->execute(array(':username' => $username, ':password' => $password));

$displayStatus = 'SUCCESS';

$displayUsername = $username;

} [/code]


[code=php]// Retrieve the user data from the database. If $row is false, then the username

// they entered is not registered.

$row = $stmt->fetch();



if($row)

{

// Verify Stored Hashed Password:

$result = password_verify($_POST['password'], $row['password']);



if ($result) {

$login_ok = true;

} else {

$errMsg = 'Invalid Credientials!';

}



}
[/code]


Obviously not the whole php scripts, but I was just trying show how easy it is to use.
Copy linkTweet thisAlerts:
@Sup3rkirbyOct 27.2014 — Some good feedback, [B]deathshadow[/B], but for my own purposes I was a bit curious about some things.

Most of that PHP code was just ripped from some other things and slapped together to provide a basic working example of what the original poster wanted. So with the [B]getDB()[/B] function (and all credentials, though they aren't in variables, only in the example for clarity), this is generally an include, allowing it to be used across all files on a site. But for the sake of asking, is that a viable way of coding such a thing?

I'm also curious about the pitfalls of pulling the password hash from the query. In the example PHP code this was only done to allow the distinction between a bad user and a bad password. I'll admit I know it's far more common to just provide an "[I]invalid username or password[/I]" message, but I have seen a few places that made the distinction and I've always appreciated that as a user. Assuming the database object, returned query results and any password variables are cleared after use, would there be any security flaws in doing so?

And my last question was about tables names (as variables). Frankly, this was something I started going recently due to table names changing. Obviously the best solution is to not be changing table names, but sometimes I don't get control over that so I found it saved me time to put the table name in a variable (in a single include script) to keep up with changes across sites. So then, in the event I was looking to have some sort of way to easily keep up with and maintain table names in queries, would there be a better way of doing so? I do suppose I could have passed the table name into the execute rather than blindly sticking it in the string, but would that be any better overall?
Copy linkTweet thisAlerts:
@deathshadowOct 28.2014 — First up an apology... the OP's post is so short I didn't even see it and thought you (sup3rkirby) were the OP. Unlike most people with their TLDR nonsense, I have the opposite failing. TSDR. My bad.

My answer to your questions is going to drag us WAY into threadjack territory, so I'm going to make another thread for this.

http://www.webdeveloper.com/forum/showthread.php?302429-securing-php-(split-from-quot-login-page-using-php-quot-)
×

Success!

Help @yahooiseeu spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...