Forum Moderators: coopster
I'll include the registration page at the bottom.
Anyway so this is my first crack at logging in based on the registered information already submitted to the database. I don't want to stick strictly to sessions without setting any clientside cookies. I know how cookies work but I'm still trying to figure sessions out.
I've read that to avoid using cookies while keeping sessions alive that an encoded session may be passed along through the url. Something like...
file.php?session=a1b2c3d4e5
I've messed with GET and POST and it seems (to me at the moment) that the GET method is used (but by default when clicking on a link) ... so I'm assuming that while logged in PHP somehow adjusts the anchors to include the session...or detects a session from the referer and handles it from there?
I'm also able to detect a POST value from a named field...
$username = $_POST['username'];
Though I am unsure of how exactly I'm supposed to "find" the $username on a specific (?row) on the database's user table. I've basically copied and pasted another script's login code in regards to the MySQL and the couple of PHP-MySQL books are going way to deep in to nitty gritty details to explain this simple part on it's own.
I have some idea that I need to assign the session a name such as the user's name (which is (or will in my case) be a unique value on a (?row) on the database's users table. Below is my not best guess at how that happens heh.
$_SESSION['username'] = $row[1];
For the sake of consistency I'll include the MySQL database and at the end the registration page. Again I'm only looking to get the most basic functions working and I'll worry about security after I figure out function!
- John
MySQL Database
CREATE TABLE `users` (
`userid` mediumint(16) NOT NULL,
`usertype` tinyint(1) NOT NULL,
`username` varchar(16) collate utf8_unicode_ci NOT NULL,
`password` varchar(16) collate utf8_unicode_ci NOT NULL,
`email` varchar(64) collate utf8_unicode_ci NOT NULL,
`namefirst` varchar(16) collate utf8_unicode_ci NOT NULL,
`namelast` varchar(32) collate utf8_unicode_ci NOT NULL,
`audio` tinyint(1) NOT NULL,
`bandwidth` tinyint(1) NOT NULL,
`dhtml` tinyint(1) NOT NULL,
`dtd` tinyint(1) NOT NULL,
`ieccss` tinyint(1) NOT NULL,
`powerkeys` tinyint(1) NOT NULL,
`theme` varchar(16) collate utf8_unicode_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
login.php
<?php
error_reporting(E_ALL);if (isset($_POST['submit'])) {
require_once ('mysql.php');$username = $_POST['username'];
$password = $_POST['password'];$query = "SELECT user_id, username FROM users WHERE username='$username' AND password=PASSWORD('$password')";
$result = @mysql_query ($query) or die(mysql_error());$_SESSION['username'] = $row[1];
} //end if post
else
{?><form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<fieldset>
<label for="username">Username: <input id="username" name="username" type="text" value="" /></label>
<br />
<label for="password">Password: <input id="pass" name="password" type="password" value="" /></label>
<br />
<input class="button" type="submit" value="Log In" /></fieldset>
</form>
<? }?>
register.php
<?php echo '<?xml version="1.0" encoding="UTF-8"?>
'; error_reporting(E_ALL);?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Registration</title>
<link href="style.css" media="screen" rel="stylesheet" title="default" type="text/css" />
<!-- saved from url=(0014)about:internet -->
</head><body>
<div class="body">
<div style="background: #069; opacity: .6;">
<?php
$referer = basename($_SERVER['HTTP_REFERER']);
echo $referer . '<br />';if(isset($_SERVER['HTTP_REFERER'])) {
include("mysql.php");
$_POST = array_map("mysql_real_escape_string",$_POST); #make sure this comes after you open the db connection, but before you define the variablesif ($_POST['audio'] == 1) {$au = "Enabled";} else {$au = "Disabled";}
if ($_POST['bandwidth'] == 1) {$bw = "Broadband";} else {$bw = "Dial-Up";}
if ($_POST['dhtml'] == 1) {$dh = "Enabled";} else {$dh = "Disabled";}
if ($_POST['dtd'] == 0) {$dtd = "XHTML 1.0 Transitional";} else if ($_POST['dtd'] == 1) {$dtd = "XHTML 1.0 Strict";} else if ($_POST['dtd'] == 2) {$dtd = "XHTML 1.1";}
if ($_POST['ieccss'] == 1) {$ie = "Enabled";} else {$ie = "Disabled";}
$pk = ($_POST['powerkeys'])? "Enabled" : "Disabled";$namefirst = $_POST['namefirst'];
$namelast = $_POST['namelast'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$audio = $_POST['audio'];
$bandwidth = $_POST['bandwidth'];
$dhtml = $_POST['dhtml'];
$dtd = $_POST['dtd'];
$ieccss = $_POST['ieccss'];
$powerkeys = $_POST['powerkeys'];
$theme = $_POST['theme'];echo 'First Name: ' . $_POST['namefirst'] . '<br />';
echo 'Last Name: ' . $_POST['namelast'] . '<br />';
echo 'Username: ' . $_POST['username'] . '<br />';
echo 'Password: (Not Shown) <br />';
echo 'Email: ' . $_POST['email'] . '<br />';
echo 'Audio: ' . $au . '<br />';
echo 'Connection: ' . $bw . '<br />';
echo 'DHTML Effects: ' . $dh . '<br />';
echo 'Doctype DTD: ' . $dh . '<br />';
echo 'IECCSS: ' . $ie . '<br />';
echo 'Power Keys: ' . $pk . '<br />';
echo 'Theme: ' . $_POST['theme'] . '<br />';$query = "INSERT INTO users (namefirst, namelast, username, password, email, audio, bandwidth, dhtml, dtd, ieccss, powerkeys, theme) VALUES ('$namefirst', '$namelast', '$username', '$password', '$email', '$audio', '$bandwidth', '$dhtml', '$dtd', '$ieccss', '$powerkeys', '$theme')";
// $result = @mysql_query ($query);
$result = @mysql_query ($query) or die(mysql_error());
}
echo $query;?>
<form action="register.php" method="post">
<fieldset>
<input name="counter" value="252" type="hidden" /><label for="namefirst">First Name: <input id="namefirst" name="namefirst" type="text" value="" /></label>
<br />
<label for="namelast">Last Name: <input id="namelast" name="namelast" type="text" value="" /></label>
<br />
<label for="username">Username: <input id="username" name="username" type="text" value="" /></label>
<br />
<label for="password">Password: <input id="pass" name="password" type="password" value="" /></label>
<br />
<label for="passwordconfirm">Confirm: <input id="passwordconfirm" name="passwordconfirm" type="password" value="" /></label>
<br />
<label for="email">E-mail Address: <input id="email" name="email" type="text" value="" /></label>
<br />
<br />
<label for="audio1"><input type="radio" checked="checked" id="audio1" name="audio" value="1" />Audio Enabled</label>
<br />
<label for="audio0"><input type="radio" id="audio0" name="audio" value="0" />Audio Disabled</label>
<br />
<br />
<label for="bandwidth1"><input type="radio" checked="checked" id="bandwidth1" name="bandwidth" value="1" />Broadband Connection</label>
<br />
<label for="bandwidth0"><input type="radio" id="bandwidth0" name="bandwidth" value="0" />Dial-Up Connection</label>
<br />
<br />
<label for="dhtml1"><input type="radio" checked="checked" id="dhtml1" name="dhtml" value="1" />DHTML Effects Enabled</label>
<br />
<label for="dhtml0"><input type="radio" id="dhtml0" name="dhtml" value="0" />DHTML Effects Disabled</label>
<br />
<br />
<label for="dtd2"><input type="radio" checked="checked" id="dtd2" name="dtd" value="2" />XHTML 1.1</label>
<br />
<label for="dtd1"><input type="radio" id="dtd1" name="dtd" value="1" />XHTML 1.0 Strict</label>
<br />
<label for="dtd0"><input type="radio" id="dtd0" name="dtd" value="0" />XHTML 1.0 Transitional</label>
<br />
<br />
<label for="ieccss1"><input type="radio" checked="checked" id="ieccss1" name="ieccss" value="1" />IECCSS Enabled</label>
<br />
<label for="ieccss0"><input type="radio" id="ieccss0" name="ieccss" value="0" />IECCSS Disabled</label>
<br />
<br />
<label for="powerkeys1"><input type="radio" checked="checked" id="powerkeys1" name="powerkeys" value="1" />Power Keys Enabled</label>
<br />
<label for="powerkeys0"><input type="radio" id="powerkeys0" name="powerkeys" value="0" />Power Keys Disabled</label>
<br />
<br />
<label for="themeclassic"><input type="radio" checked="checked" id="themeclassic" name="theme" value="classic" />Classic Theme</label>
<br />
<label for="themecity"><input type="radio" id="themecity" name="theme" value="city" />City Blue Theme</label>
<br />
<label for="themelavender"><input type="radio" id="themelavender" name="theme" value="lavender" />Lavender Theme</label>
<br />
<label for="themematrix"><input type="radio" id="themematrix" name="theme" value="matrix" />Matrix Theme</label>
<br />
<input class="button" type="submit" value="Register" />
</fieldset>
</form></div>
</body>
</html>
Right now I'm trying to figure out the select command to spit out the table or parts of it. From there I'm going to try and figure out how to find a user in a table column.
Here is an example that I've tried though without any success...
$dump = "SELECT * from userid";
$giveuserid = @mysql_query ($dump) or die(mysql_error());
echo $giveuserid;
With error_reporting(E_ALL); I'm not getting any errors though this quoted code only happens if the page was posted to so I'm not sure if the request is even hitting the DB?
- John
* Edit *
I've made the following changes... I'm guessing the row order is how they are displayed vertically in PHPMyAdmin? Since username is the third row that would make taking the $result for the username to be taken from row3?
$query = "SELECT userid, username FROM users WHERE username='$username' AND password=PASSWORD('$password')";
$result = @mysql_query ($query) or die(mysql_error());
$row = mysql_fetch_array ($result, MYSQL_NUM);
$_SESSION['username'] = $row[3];
$_SESSION['user_id'] = $row;
[1][edited by: JAB_Creations at 9:48 pm (utc) on Mar. 8, 2007]
1.) Information already exists in database.
2.) User submits log-in username and password.
3.) Log-in page makes a POST method. Detect if the page has made a POST.
3.) PHP based Log-in script captures POST(ed) information and turns it in to variables.
$namefirst = $_POST['namefirst'];
$password = $_POST['password'];
4.) The PHP script now has to call the database by now at least.
include("mysql.php");
5.) The PHP script now has to select the table and search and compare the POST information with a potential row?
$query = "SELECT userid, username FROM users WHERE username='$username' AND password=PASSWORD('$password')";
$result = @mysql_query ($query) or die(mysql_error());
6.) If the user is found it has to assign the user's information to a session?
This is where everything gets foggy though it would be best if we could handle the script in baby steps like this. I really want to learn this instead of copying and pasting some other script.
- John
That's it, you're safe from an SQL injection attack via those two variables. You don't even have to understand why or how it works.
The conversation to extract data from a database is:
In your query in your previous post, you asked mysql for a two-part answer: id and name. However, when assigning the session variables, you put the 4th part into name and the whole kit & kaboodle into user id.
This is a little bit of an aside but bear with me for a moment. Let's say I put the answers those five people gave me into a database table and now I want to get the information back out. Assuming step 1 in my list above is being performed by your "mysql.php" script, this is how it would look:
$query_resource_id = mysql_query("SELECT username, address, telephone FROM users") or die(mysql_error());
while($one_row = mysql_fetch_array($query_resource_id)) {
echo $one_row['username']; // Echos the name to the browser
echo $one_row[0]; // This also echos the name to the browser - mysql_fetch_array returns both numerically indexed and 'named' parts (columns)
echo $one_row['address'];
echo $one_row['telephone'];
} // EndWhile getting answers one row at a time
mysql_free_result($query_resource_id);
That while loop will go through 5 times. The first time will have the first person's 3-part answer, the second time will have the second person's, etc. After the while loop, I close the query. It's a good habit to develop.
Now back to your query:
$query = "SELECT userid, username FROM users WHERE username='$username' AND password=PASSWORD('$password')";
$result = mysql_query ($query) or die(mysql_error());
if(mysql_num_rows($result) == 0) {
mysql_free_result($result);
// the name and/or password didn't match, so handle appropriately
} // EndIf no rows match
else {
$one_row = mysql_fetch_array($result); // Now we have an array that has 4 elements. [0] and ['userid'] are two, what are the others?
mysql_free_result($result);
// Here we have an authenticated user, now what?
} // EndElse log the user in
'now what' can be any number of things. The next baby step is:
$_SESSION['username'] = $row['username']; // Inside the else
You don't have to store the user's information; you can store whatever might come in handy later - you're tracking the user by the session itself. For example, you could just set $_SESSION['loggedin'] = true;
Then at the top of each script you want to protect, you start the session and see if the person is 'logged in':
session_start();
if(!isset($_SESSION['username'])) { // Or 'loggedin'
echo "sorry you can't access this page";
} // EndIf not logged user
else {
} // EndElse do the voodoo
The next step after that is to decide how long your users stay signed in. Do you want to gather any information, like when the person signed in, the IP address? Can one person be signed in from 80 different places? How do you handle lost passwords?
What I generally do is have a separate table for sessions. When the person signs in an entry is inserted into the session table, which has fields for signin time, last activity time, IP address, permissions mask, etc. As the person moves around the web site the last activity time gets updated. Any time anyone at all moves around the web site, a function deletes any session entries with last activity times older than x seconds. And of course the session entry is deleted if the user signs out.
but you really need to do it from day 1, not day 43 or day 186.
I can't agree more. Security goes to the bone.
I'm running a wiki in our company intranet, and I had to completely gut their security model (egalitarian and optimistic), and replace it with a much more pessimistic system.
The security applies EVERYWHERE. It's like playing whack-a-mole. I had to make some pretty massive, fundamental changes to make it work.
If you know anything about Wiki, security ain't the highest priority. Quite the opposite, in fact.
This has been an education.
If that is all that I need to do to secure major holes in the script then great! I really want to break in to security though I try to keep developer related things broken down to as simple as I can get them. I think that is why for the most part JavaScript was easy for me to get in to with certain things.
I've gone ahead and cleaned up the variables so that they all match. What I've really noticed is with what I have now I'm doing something wrong from the very start! I'm checking for a referer and not a POST (that of course is from the (this) page refer!)
How do I change if(isset($_SERVER['HTTP_REFERER'])) in to something that detects the POST referer?
Without doing anything too fancy I would imagine I would set the referer as a variable...
$refer = $_SERVER['HTTP_REFERER']);
...and then detect what page POST(ed) to this?
That is also something I've always wanted to figure out, how to allow or disallow POST from different domains. ;)
Once I get this part working I'll reread your post and compare it to what I was doing in the first place (minus the mixed up variables, gah!)
I think that first line is why I'm having really weird stuff happen with what I have now. I'm not finding anything about "POST referer" in regards to PHP. I'm sure such a thing would have it's own can of worms worth of topics to be discussed?
I really wish I was not short on time otherwise I'd POST (;)) more but this is what I have. Thanks for everyone's help so far! When I finally strike it rich I promise to get a membership. :)
- John
<?php
error_reporting(E_ALL);if(isset($_SERVER['HTTP_REFERER']))
{
$referer = basename($_SERVER['HTTP_REFERER']);
require_once ('mysql.php');
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);$query = "SELECT userid, username FROM users WHERE username='$username' AND password=PASSWORD('$password')";
$result = mysql_query ($query) or die(mysql_error());if(mysql_num_rows($result) == 0)
{
mysql_free_result($result);
// the name and/or password didn't match, so handle appropriately
} // EndIf no rows matchelse
{
$one_row = mysql_fetch_array($result); // Now we have an array that has 4 elements. [0] and ['userid'] are two, what are the others?
mysql_free_result($result);
// Here we have an authenticated user, now what?
echo 'logged in';
} // EndElse log the user in
?><form action="<?php echo basename($_SERVER['PHP_SELF']);?>" method="POST">
<fieldset>
<label for="username">Username: <input id="username" name="username" type="text" value="" /></label>
<br />
<label for="password">Password: <input id="pass" name="password" type="password" value="" /></label>
<br />
<input class="button" type="submit" value="Log In" /></fieldset>
</form>
<?
}
if(isset($_SERVER['HTTP_REFERER']))
{
echo basename($_SERVER['HTTP_REFERER']);
}
?>
<br />
<a href="<?php echo $_SERVER['PHP_SELF'];?>">This Page Link</a>
I'm not getting any PHP error messages. I've implemented a little scripting that will echo in regards to blank a username, password, or both. This bit is great for troubleshooting.
I've also made sure that it only accepts POST method from itself (as in no one can log in through a different file or domain name)...or at least that was my intent!
I've made spaces (that won't appear below) to help make the code more readable. To me however it's very readable at least. Every next deeper if has the next line start with { one space further to the right.
Anyway the problem I'm having right now is that it keeps telling me my username and password didn't match. I've also copied another script's comparison "part" just to see if it might be syntax.
My Current Script
<?php
error_reporting(E_ALL);$referer = basename($_SERVER['HTTP_REFERER']);
$request = $_SERVER['REQUEST_METHOD'];
$require = basename($_SERVER['PHP_SELF']);if ($request == "POST" && $referer == $require) // check for self-post
{
require_once ('mysql.php');if(empty($_POST['username'])){$username = FALSE; echo '<b>empty username</b><br />';}
else {$username = mysql_real_escape_string($_POST['username']);}if(empty($_POST['password'])){$password = FALSE; echo '<b>empty password</b><br />';}
else {$password = mysql_real_escape_string($_POST['password']);}if ($username && $password)
{
$query = "SELECT userid, username FROM users WHERE username='$username' AND password=PASSWORD('$password')";
$result = mysql_query ($query) or die(mysql_error());if(mysql_num_rows($result) == 0)
{
mysql_free_result($result); // the name and/or password didn't match, so handle appropriately
echo '<b>Wrong username and or password!</b><br />';
}// EndIf no rows match
else
{
$one_row = mysql_fetch_array($result); // Now we have an array that has 4 elements. [0] and ['userid'] are two, what are the others?
mysql_free_result($result);
if ($one_row) // Here we have an authenticated user, now what?
{
echo '<br /><br /><span style="color: #f00;">Logged In!</span><br /><br />';
}
} // EndElse log the user in
}
}
?><form action="<?php echo basename($_SERVER['PHP_SELF']);?>" method="POST">
<fieldset>
<?php if ($username = FALSE) {echo '<br /><span style="color: #f00;">No or incorrect username</span><br />';}?>
<label for="username">Username: <input id="username" name="username" type="text" value="" /></label>
<br />
<?php if ($password = FALSE) {echo '<br /><span style="color: #f00;">No or incorrect username</span><br />';}?>
<label for="password">Password: <input id="pass" name="password" type="password" value="" /></label>
<br />
<input class="button" type="submit" value="Log In" /></fieldset>
</form>
<br />
<a href="<?php echo basename($_SERVER['PHP_SELF']);?>">Link to this page to set referer.</a>
Same script though with a different attempt to match username and password
<?php
error_reporting(E_ALL);$referer = basename($_SERVER['HTTP_REFERER']);
$request = $_SERVER['REQUEST_METHOD'];
$require = basename($_SERVER['PHP_SELF']);if ($request == "POST" && $referer == $require) // check for self-post
{
require_once ('mysql.php');if(empty($_POST['username'])){$username = FALSE; echo '<b>empty username</b><br />';}
else {$username = mysql_real_escape_string($_POST['username']);}if(empty($_POST['password'])){$password = FALSE; echo '<b>empty password</b><br />';}
else {$password = mysql_real_escape_string($_POST['password']);}if ($username && $password)
{
$query = "SELECT userid, username FROM users WHERE username='$username' AND password=PASSWORD('$password')";
$result = mysql_query ($query) or die(mysql_error());$row = mysql_fetch_array ($result, MYSQL_NUM);
if ($row) { // A match was made.
// Start the session, register the values & redirect.
$_SESSION['first_name'] = $row[1];
$_SESSION['user_id'] = $row[0];ob_end_clean(); // Delete the buffer.
header ("Location: [localhost...]
exit();} else { // No match was made.
echo '<p><font color="red" size="+1">The username and password entered do not match those on file.</font></p>';
}mysql_close(); // Close the database connection.
}}/*
if(mysql_num_rows($result) == 0)
{
mysql_free_result($result); // the name and/or password didn't match, so handle appropriately
echo '<b>Wrong username and or password!</b><br />';
}// EndIf no rows match
else
{
$one_row = mysql_fetch_array($result); // Now we have an array that has 4 elements. [0] and ['userid'] are two, what are the others?
mysql_free_result($result);
if ($one_row) // Here we have an authenticated user, now what?
{
echo '<br /><br /><span style="color: #f00;">Logged In!</span><br /><br />';
}
} // EndElse log the user in
}
}
*/
?>
<form action="<?php echo basename($_SERVER['PHP_SELF']);?>" method="POST">
<fieldset>
<?php if ($username = FALSE) {echo '<br /><span style="color: #f00;">No or incorrect username</span><br />';}?>
<label for="username">Username: <input id="username" name="username" type="text" value="" /></label>
<br />
<?php if ($password = FALSE) {echo '<br /><span style="color: #f00;">No or incorrect username</span><br />';}?>
<label for="password">Password: <input id="pass" name="password" type="password" value="" /></label>
<br />
<input class="button" type="submit" value="Log In" /></fieldset>
</form>
<br />
<a href="<?php echo basename($_SERVER['PHP_SELF']);?>">Link to this page to set referer.</a>
I've been looking for minor errors and such (such as mismatching variables, etc).
The obvious part to me is that somehow it's not finding the username otherwise it would match. If it is finding the username it's not able to match. But I'm not fluent enough with the syntax to pick spot this bug. Thanks for the continued help!
- John
Make sure to read the code reviews [webmasterworld.com] as they address certain issues that weren't addressed in the thread I linked to above.
<?php if ($username = FALSE) {echo '<br /><span style="color: #f00;">No or incorrect username</span><br />';}?>
I'm not seeing anything else really wrong with the script. I would suggest running the script once with:
$username .= '1';
$query = "INSERT INTO users (username,password) VALUES ('$username',PASSWORD('$password'))"
in place of the SELECT, then look at the two rows in phpMyAdmin - I bet the passwords don't match. If that's the case, copy the field value from the second into the first, delete the second entry, change the script back and see what happens.
You're gonna love reading this, but referers are easy to set client-side so your efforts up at the top aren't exactly bullet-proof. I hate to give you even more to read, but see if my post in this thread makes any sense (they didn't cover this aspect in the authentication thread):
The Battle Against Form Spam [webmasterworld.com]
Notice: Undefined variable: username on line 13
Alas I keep forgetting a single = is assignment and == is a relative comparison (with === being an absolute comparison correct?)
What I'm thinking right now is that I don't at least one of three things: a session, a cookie, or something being passed through the URL. Now I'm not completely sure but the user might be logged in at least on this page directly after the POST. Either way I'm guessing there will be a problem remaining logged in.
I've got lots of ideas on how I'll combat spam though I'm not going to publicly list them. ;) The next version of my site will have at least twice the security strength that the live version currently has. It's just not a topic I like to discuss publicly if possible. I've hit resistance from some folks on forcing the POST to be from the referer I choose but I plan on warning the visitor of potential threat to their account if they send their password locally or elsewhere without it first being encrypted. I think that is a very worthy security feature. If it's a search POST then obviously it would not be important to implement in my view. I know no single security feature is bullet proof which is why I enjoy the challenge of creating ever more complex methods of blocking spam without legitimate users noticing much if anything.
As far as security goes for the moment until we get this working I'll just stick with the MySQL injection addition for the moment until we get this thing working! Then once it's working (across several pages that is!) I'll start messing with MD5 and SHA1. Matter of fact I am considering giving an advanced options (kind of hidden to less savvy users) to let visitors choose their preferred encryption type because I rock like that. ;)
Back to the not working script (;)), I'm absolutely sure that the username and password are correct. I've also checked to make sure that the PHP script is looking in the correct columns (username, password) which they are so I'm not making any goofy mistakes.
Anyway here is everything with obvious values changed (username/password) and set to "test" for all that. Thanks!
- John
login.php
<?php
error_reporting(E_ALL);$referer = basename($_SERVER['HTTP_REFERER']);
$request = $_SERVER['REQUEST_METHOD'];
$require = basename($_SERVER['PHP_SELF']);if ($request == "POST" && $referer == $require) // check for self-post
{
require_once ('mysql.php');if(empty($_POST['username'])){$username == FALSE; echo '<b>empty username</b><br />';}
else {$username = mysql_real_escape_string($_POST['username']);}if(empty($_POST['password'])){$password == FALSE; echo '<b>empty password</b><br />';}
else {$password = mysql_real_escape_string($_POST['password']);}if ($username && $password)
{
$query = "SELECT userid, username FROM users WHERE username='$username' AND password=PASSWORD('$password')";
$result = mysql_query ($query) or die(mysql_error());if(mysql_num_rows($result) == 0)
{
mysql_free_result($result); // the name and/or password didn't match, so handle appropriately
echo '<b>Wrong username and or password!</b><br />';
}// EndIf no rows match
else
{
$one_row = mysql_fetch_array($result); // Now we have an array that has 4 elements. [0] and ['userid'] are two, what are the others?
mysql_free_result($result);
if ($one_row) // Here we have an authenticated user, now what?
{
echo '<br /><br /><span style="color: #f00;">Logged In!</span><br /><br />';
}
} // EndElse log the user in
}
}
?><form action="<?php echo basename($_SERVER['PHP_SELF']);?>" method="POST">
<fieldset>
<?php if ($username == FALSE) {echo '<br /><span style="color: #f00;">No or incorrect username</span><br />';}?>
<label for="username">Username: <input id="username" name="username" type="text" value="" /></label>
<br />
<?php if ($password == FALSE) {echo '<br /><span style="color: #f00;">No or incorrect username</span><br />';}?>
<label for="password">Password: <input id="pass" name="password" type="password" value="" /></label>
<br />
<input class="button" type="submit" value="Log In" /></fieldset>
</form>
<br />
<a href="<?php echo basename($_SERVER['PHP_SELF']);?>">Link to this page to set referer.</a>
mysql.php
<?php
DEFINE ('DB_USER', 'test');
DEFINE ('DB_PASSWORD', 'test');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'test');$dbc = @mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to MySQL: ' . mysql_error() );
mysql_select_db (DB_NAME) OR die ('Could not select the database: ' . mysql_error() );
?>
MySQL Export
CREATE TABLE `users` (
`userid` mediumint(16) NOT NULL auto_increment,
`usertype` tinyint(1) NOT NULL,
`username` varchar(16) collate utf8_unicode_ci NOT NULL,
`password` varchar(32) collate utf8_unicode_ci NOT NULL,
`email` varchar(64) collate utf8_unicode_ci NOT NULL,
`namefirst` varchar(16) collate utf8_unicode_ci NOT NULL,
`namelast` varchar(32) collate utf8_unicode_ci NOT NULL,
`audio` tinyint(1) NOT NULL,
`bandwidth` tinyint(1) NOT NULL,
`dhtml` tinyint(1) NOT NULL,
`dtd` tinyint(1) NOT NULL,
`ieccss` tinyint(1) NOT NULL,
`powerkeys` tinyint(1) NOT NULL,
`theme` varchar(16) collate utf8_unicode_ci NOT NULL,
PRIMARY KEY (`userid`),
KEY `userid` (`userid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=19 ;--
-- Dumping data for table `users`
--INSERT INTO `users` VALUES (1, 0, 'test', 'test', 'test@example.com', 'John', 'Bilicki', 1, 1, 1, 2, 1, 1, 'classic');
$query = "SELECT userid, username FROM users WHERE username='$username' AND password='$password'";
Now the main question that remains in regards to functionality is how do I keep them logged in?
Is a cookie recommended or not? I guess we need a session and I've been reading about them in the books I have. I'm also looking at some example scripts. Once the user can browse a different page and click between the pages without being logged out I'll try to figure out encoding the password and patching up the comparison. Thanks for the continued help!
- John
Once the user can browse a different page and click between the pages without being logged out
A session remains viable as long as the user keeps their browser open. They don't have to remain on your site.
The latest Gecko/Mozilla engine has session resumption stuff in it, but I haven't played with it much.
I've added a session and it seems to be that which created the cookie. I'd like to be able to modify the cookie as I please however such as it's name instead of using PHPSESSID.
if ($one_row) // Here we have an authenticated user, now what?
{
session_start();
$_SESSION['username'] = $username; // store session data
echo "Username = ". $_SESSION['username']; //retrieve data
echo '<br /><br /><span style="color: #f00;">Logged In!</span><br /><br />';
}
I also have another page trying to read the session but it's not happening successfully.
- John
test.php
<?phpecho '<h1>Welcome';
if (isset($_SESSION['username'])) {
echo ", {$_SESSION['username']}!";
}
else {
echo ' Unknown person!';
}
echo '</h1>';
?>
The idea is that just setting values into $_SESSION[] acts as a "transportable global," and becomes available to all files while the browser is open.
It is also more secure, as the contents of $_SESSION are never sent to the browser.
If you want to use a different name, use:
session_name [php.net]('JAB');
before the session_start line in both your login script and any other file (like test.php) that wants to read the session.
You can set other cookies on your visitors' browsers, but as cmarshall said, the beauty of using the SESSION mechanism is that the data you store doesn't get sent back and forth with each browser request - it stays on the server.
Today's Goal: Clientside encryption via JavaScript. Looking at the database should easily tell me if I have it working or not I would imagine. I've already done a Google for "JavaScript MD5" and the first result looks promising (not sure if I can post the link though).
There are some other things I want to clean up and I'll post what I have later today. Thanks!
- John
1.) I can't log out! Gah... I've tried...
session_destroy();
session_unset();
unset($_SESSION['username']);
Of course I started the session on the page to begin with and gave it a name of "username"...
2.) I'm still not sure how to rename the cookie name from PHPSESSID to say "member". Firefox --> Tools --> Options --> Privacy --> Show Cookies --> localhost --> PHPSESSID --> Look for pain killers.
In the header.php file I include in every php file I have this at the top...
session_start(); $session = session_name ("username");
The login script has this...
session_start();
$_SESSION['username'] = $username; // store session data
Not sure how to append that to for the cookie to change it from "PHPSESSID" to "member"?
3.) If I want to display the user's first name and it's the third row in the column do I do something like echo $row[3];? Do I have to have any other special syntax? Thanks!
- John
logout.php
<?php
session_start(); $session = session_name ("username");
unset($_SESSION['username']);
$referer = basename($_SERVER['HTTP_REFERER']);
header("Location: $referer");
?>
So all I want to figure out now to smooth the script out is the reference MySQL values, rename the cookie...
...and I will bring a couple of PHP books with me to work to read about stopping duplicate usernames. I guess I'll mention that in the other thread later tonight though. Thanks for the continued help!
- John
Set the field as a unique field in MySQL. I also use AJAX to dynamically look up a username as it's being typed in.
This can have security implications, as it could be used in a brute-force username guess, but, since this is for an internal Wiki, any cracker that got this far would have had to pick some far more stringent locks, and all the people here can guess usernames without need for a brute-force approach.
You can also do a quick lookup in MySQL for the username after it's typed in, and reject it if it's a dupe.
login.php
<?php
error_reporting(E_ALL);
$session = session_name("member");
session_start();if (isset($_SESSION['member'])) {header("Location: status.php"); exit;}
echo '<h1>Welcome';
if (isset($_SESSION['member'])) {
echo ", {$_SESSION['member']}!";
echo '</h1>';
}
else {
echo ' Stranger!';
echo '</h1>';}
echo '<a href="status.php">Status</a>';$request = $_SERVER['REQUEST_METHOD'];
$referer = basename($_SERVER['HTTP_REFERER']);
$domain = $_SERVER['HTTP_HOST'];
$refdomain = $_SERVER['HTTP_REFERER'];
$refdomain = preg_replace("/http:\/\//i", "", $refdomain);
$refdomain = preg_replace("/^www\./i", "", $refdomain );
$refdomain = preg_replace("/\/.*/i", "", $refdomain );if ($request == "POST" && $refdomain == $domain)
{
require_once ('mysql.php');if(empty($_POST['member'])){$username == FALSE; echo '<b>empty username</b><br />';}
else {$username = mysql_real_escape_string($_POST['member']);}if(empty($_POST['password'])){$password == FALSE; echo '<b>empty password</b><br />';}
else {$password = mysql_real_escape_string($_POST['password']);}if ($username && $password)
{
$query = "SELECT userid, username FROM users WHERE username='$username' AND password='$password'";
$result = mysql_query ($query) or die(mysql_error());if(mysql_num_rows($result) == 0)
{
mysql_free_result($result); // the name and/or password didn't match, so handle appropriately
echo '<b>Wrong username and or password!</b><br />';
}// EndIf no rows match
else
{
$one_row = mysql_fetch_array($result); // Now we have an array that has 4 elements. [0] and ['userid'] are two, what are the others?
mysql_free_result($result);if ($one_row) // Here we have an authenticated user, now what?
{
$_SESSION['member'] = $username; // store session data
session_start();
echo "Username = ". $_SESSION['member']; //retrieve data
echo '<br /><br /><span style="color: #f00;">Logged In!</span><br /><br />';
echo '<a href="status.php">check status?</a>';
}
} // EndElse log the user in
}
}
?><form action="<?php echo basename($_SERVER['PHP_SELF']);?>" method="POST">
<fieldset>
<?php if ($username == FALSE) {echo '<br /><span style="color: #f00;">No or incorrect username</span><br />';}?>
<label for="username">Username: <input id="username" name="username" type="text" value="" /></label>
<br />
<?php if ($password == FALSE) {echo '<br /><span style="color: #f00;">No or incorrect username</span><br />';}?>
<label for="password">Password: <input id="pass" name="password" type="password" value="" /></label>
<br />
<input class="button" type="submit" value="Log In" /></fieldset>
</form>
<br />
<a href="<?php echo basename($_SERVER['PHP_SELF']);?>">Link to this page to set referer.</a>
<br />
<a href="logged_in.php">logged_in.php</a>
Now I've got a small sidebar area that is for either signing in or options and signing out. I include one file or another and here is the code for that...
if (!isset($_SESSION['member'])) {include("member-sign-in.php");}
if (isset($_SESSION['member'])) {include("member-sign-out.php");}
Keeping in mind this is how I'm creating the session...
$session = session_name ("member");
session_start();
I'm assuming because the cookie is set that the session is still being made just under the different cookie name...so therefor do I have to make a change to how I call that session?
Also I made the username row a ?key row...is that what was intended? Thanks!
- John