Page 1 of 3

PHP Login System

Posted: Mon Mar 17, 2014 11:51 pm
by OpenSourceFan
Hello! I am a somewhat experienced HTML and CSS web developer who is delving into PHP and JavaScript for the first time. I am also an employee for a small business owner who is need of a simple PHP login system that will display some information for a select group of people. I would like to eventually take the time to learn PHP fully and properly, but I am a bit rushed as it is to produce an immediate result and would greatly appreciate any help offered.

I found a PHP basic membership login system already prebuilt at this tutorial: http://www.developphp.com/view.php?tid=762 For the most part, it suits my needs (I can connect to a database on HostMonster), but I need a few modifications.

Firstly, my boss does not want a system with a username and password login, but rather just a simple password only login. Yes, not very secure, but my boss has his reasons for it. My question is: What do I need to remove and/or add to make a simple password only login system?

This is the script from the index.php page:

Code: Select all

<?php
session_start(); // Must start session first thing
/* 
Created By Adam Khoury @ www.flashbuilding.com 
-----------------------June 20, 2008----------------------- 
*/
// See if they are a logged in member by checking Session data
$toplinks = "";
if (isset($_SESSION['id'])) {
	// Put stored session variables into local php variable
    $userid = $_SESSION['id'];
    $username = $_SESSION['username'];
	$toplinks = '<a href="member_profile.php?id=' . $userid . '">' . $username . '</a> &bull; 
	<a href="member_account.php">Account</a> &bull; 
	<a href="logout.php">Log Out</a>';
} else {
	$toplinks = '<a href="join_form.php">Register</a> &bull; <a href="login.php">Login</a>';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My Homepage</title>
<style type="text/css">
<!--
body {margin: 0px}
-->
</style></head>

<body>
<table style="background-color: #CCC" width="100%" border="0" cellpadding="12">
  <tr>
    <td width="78%"><h1>My Website Logo</h1></td>
    <td width="22%"><?php echo $toplinks; ?></td>
  </tr>
</table>
<div style="padding:12px">
  <h2>Welcome to the home page of my website.</h2>
  <p>This is where we do a summary or showcase of  content the site has to offer.</p>
</div>
</body>
</html>
This is the script from the login.php page:

Code: Select all

<?php
/* 
Created By Adam Khoury @ www.flashbuilding.com 
-----------------------June 20, 2008----------------------- 
*/
if ($_POST['email']) {
//Connect to the database through our include 
include_once "connect_to_mysql.php";
$email = stripslashes($_POST['email']);
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
$password = ereg_replace("[^A-Za-z0-9]", "", $_POST['password']); // filter everything but numbers and letters
$password = md5($password);
// Make query and then register all database data that -
// cannot be changed by member into SESSION variables.
// Data that you want member to be able to change -
// should never be set into a SESSION variable.
$sql = mysql_query("SELECT * FROM members WHERE email='$email' AND password='$password' AND emailactivated='1'"); 
$login_check = mysql_num_rows($sql);
if($login_check > 0){ 
    while($row = mysql_fetch_array($sql)){ 
        // Get member ID into a session variable
        $id = $row["id"];   
        session_register('id'); 
        $_SESSION['id'] = $id;
        // Get member username into a session variable
	    $username = $row["username"];   
        session_register('username'); 
        $_SESSION['username'] = $username;
        // Update last_log_date field for this member now
        mysql_query("UPDATE members SET lastlogin=now() WHERE id='$id'"); 
        // Print success message here if all went well then exit the script
		header("location: member_profile.php?id=$id"); 
		exit();
    } // close while
} else {
// Print login failure message to the user and link them back to your login page
  print '<br /><br /><font color="#FF0000">No match in our records, try again </font><br />
<br /><a href="login.php">Click here</a> to go back to the login page.';
  exit();
}
}// close if post
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Login to your profile</title>
<script type="text/javascript">
<!-- Form Validation -->
function validate_form ( ) { 
valid = true; 
if ( document.logform.email.value == "" ) { 
alert ( "Please enter your User Name" ); 
valid = false;
}
if ( document.logform.pass.value == "" ) { 
alert ( "Please enter your password" ); 
valid = false;
}
return valid;
}
<!-- Form Validation -->
</script>
</head>
<body>
     <div align="center">
       <h3><br />
         <br />
       Log in to your account here<br />  
       <br />
       </h3>
     </div>
     <table align="center" cellpadding="5">
      <form action="login.php" method="post" enctype="multipart/form-data" name="logform" id="logform" onsubmit="return validate_form ( );">
        <tr>
          <td class="style7"><div align="right">Email Address:</div></td>
          <td><input name="email" type="text" id="email" size="30" maxlength="64" /></td>
        </tr>  
        <tr>
          <td class="style7"><div align="right">Password:</div></td>
          <td><input name="password" type="password" id="password" size="30" maxlength="24" /></td>
        </tr>
        <tr>
          <td>&nbsp;</td>
          <td><input name="Submit" type="submit" value="Login" /></td>
        </tr>
      </form>
    </table>
</body>
</html>
Second, I need a way to prevent users from changing their account information with this login system. Can I just delete the links to the member account and member profile pages? And if I do, how do I tell the login system to take the user to a page where the user sees information from a MySQL table.

There are other things I may need to ask, but this is a start.

Thanks!

Re: PHP Login System

Posted: Tue Mar 18, 2014 8:45 am
by Celauran
Replacing this

Code: Select all

$sql = mysql_query("SELECT * FROM members WHERE email='$email' AND password='$password' AND emailactivated='1'"); 
with this

Code: Select all

$sql = mysql_query("SELECT * FROM members WHERE password='$password'"); 
will check for password only.
Second, I need a way to prevent users from changing their account information with this login system. Can I just delete the links to the member account and member profile pages?
Remove forms from those pages. The users will be able to see the data, but it will effectively become read-only.
how do I tell the login system to take the user to a page where the user sees information from a MySQL table.
Looks like that's already being handled

Code: Select all

header("location: member_profile.php?id=$id"); 
exit();

Re: PHP Login System

Posted: Thu Mar 20, 2014 5:17 am
by hybris
I guess you could also skip the user name input box on the login name and submit the username as a hidden field.

This would allow for have a standarduser where you only need to submit the pw or you could have a link to advanced login where the user can supply both username and pw (for admin access or something)...

http://www.wikihow.com/Create-a-Secure- ... -and-MySQL

^^ Great tutorial for php login script

Re: PHP Login System

Posted: Sun Mar 23, 2014 6:00 pm
by OpenSourceFan
Thank you both for replying. I apologize for taking so long to reply, I have had a busy week at work and have had little time to work on this project.
Celauran wrote:Replacing this

Code: Select all

$sql = mysql_query("SELECT * FROM members WHERE email='$email' AND password='$password' AND emailactivated='1'"); 
with this

Code: Select all

$sql = mysql_query("SELECT * FROM members WHERE password='$password'"); 
will check for password only.
I made this change and it works, thank you! However, there is still an HTML section with a field that asks for an email address.

Code: Select all

        <tr>
          <td class="style7"><div align="right">Email Address:</div></td>
          <td><input name="email" type="text" id="email" size="30" maxlength="64" /></td>
        </tr>
When I removed that field, pressing enter had the effect of merely refressing the page and I could not login. I also noticed a JavaScript code that seemed related:

Code: Select all

<script type="text/javascript">
<!-- Form Validation -->
function validate_form ( ) { 
valid = true; 
if ( document.logform.email.value == "" ) { 
alert ( "Please enter your User Name" ); 
valid = false;
}
if ( document.logform.pass.value == "" ) { 
alert ( "Please enter your password" ); 
valid = false;
}
return valid;
}
<!-- Form Validation -->
</script>
I tried removing the part that asks for an email address by using <!-- and -->, but no luck.

Is there any thing else about the original code I posted that I need to remove or adjust to keep my login system from asking for an email address?
hybris wrote:I guess you could also skip the user name input box on the login name and submit the username as a hidden field.

This would allow for have a standarduser where you only need to submit the pw or you could have a link to advanced login where the user can supply both username and pw (for admin access or something)...
I'll read your article, but I would prefer to just have no code that references the need for a username or email address of any sort, as that's essentially what is being required for the job. I do appreciate your suggestion though.
Celauran wrote:
Second, I need a way to prevent users from changing their account information with this login system. Can I just delete the links to the member account and member profile pages?
Remove forms from those pages. The users will be able to see the data, but it will effectively become read-only.
how do I tell the login system to take the user to a page where the user sees information from a MySQL table.
Looks like that's already being handled

Code: Select all

header("location: member_profile.php?id=$id"); 
exit();
I changed what came after location at it worked, it took me/the user to a specific .php page. Thus, I don't have to bother with the pages that allow the user to mess around with the member account and member profile pages. Again, thank you!

Re: PHP Login System

Posted: Sun Mar 23, 2014 6:09 pm
by Celauran
OpenSourceFan wrote:However, there is still an HTML section with a field that asks for an email address.

Code: Select all

        <tr>
          <td class="style7"><div align="right">Email Address:</div></td>
          <td><input name="email" type="text" id="email" size="30" maxlength="64" /></td>
        </tr>
When I removed that field, pressing enter had the effect of merely refressing the page and I could not login. I also noticed a JavaScript code that seemed related:

Code: Select all

<script type="text/javascript">
<!-- Form Validation -->
function validate_form ( ) { 
valid = true; 
if ( document.logform.email.value == "" ) { 
alert ( "Please enter your User Name" ); 
valid = false;
}
if ( document.logform.pass.value == "" ) { 
alert ( "Please enter your password" ); 
valid = false;
}
return valid;
}
<!-- Form Validation -->
</script>
I tried removing the part that asks for an email address by using <!-- and -->, but no luck.
JS comments are of the same form as PHP comments, and not like HTML comments. You can remove lines with // or blocks with /* ... removed ... */
You could comment out the block checking that the email field is not empty, you could delete the block, or, IMO, you could delete that chunk of JS entirely.

Re: PHP Login System

Posted: Mon Mar 24, 2014 1:33 am
by OpenSourceFan
Celauran wrote:
OpenSourceFan wrote:However, there is still an HTML section with a field that asks for an email address.

Code: Select all

        <tr>
          <td class="style7"><div align="right">Email Address:</div></td>
          <td><input name="email" type="text" id="email" size="30" maxlength="64" /></td>
        </tr>
When I removed that field, pressing enter had the effect of merely refressing the page and I could not login. I also noticed a JavaScript code that seemed related:

Code: Select all

<script type="text/javascript">
<!-- Form Validation -->
function validate_form ( ) { 
valid = true; 
if ( document.logform.email.value == "" ) { 
alert ( "Please enter your User Name" ); 
valid = false;
}
if ( document.logform.pass.value == "" ) { 
alert ( "Please enter your password" ); 
valid = false;
}
return valid;
}
<!-- Form Validation -->
</script>
I tried removing the part that asks for an email address by using <!-- and -->, but no luck.
JS comments are of the same form as PHP comments, and not like HTML comments. You can remove lines with // or blocks with /* ... removed ... */
You could comment out the block checking that the email field is not empty, you could delete the block, or, IMO, you could delete that chunk of JS entirely.
Okay, just tried all that. Unfortunately, no luck.

Perhaps it has something to do with this?

Code: Select all

if ($_POST['email']) {
//Connect to the database through our include 
include_once "connect_to_mysql.php";
$email = stripslashes($_POST['email']);
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
$password = ereg_replace("[^A-Za-z0-9]", "", $_POST['password']); // filter everything but numbers and letters
$password = md5($password);

Re: PHP Login System

Posted: Mon Mar 24, 2014 5:44 am
by Celauran
Ah yes, of course. I had only looked at the code in your most recent post and hadn't gone back to look at the original.

Code: Select all

if (isset($_POST['password']) && !empty($_POST['password'])) {
//Connect to the database through our include
include_once "connect_to_mysql.php";
$password = ereg_replace("[^A-Za-z0-9]", "", $_POST['password']); // filter everything but numbers and letters
$password = md5($password);
...etc
Note that both restricting which characters can be contained within a password and using md5 to hash said password are pretty bad practices. I've left that bit alone because I don't want to break your existing login system, but it's something worth keeping in mind going forward.

Re: PHP Login System

Posted: Mon Mar 24, 2014 12:39 pm
by hybris
Do you want different users (each one with their own password) or is it enough to have 1 user with a company pw (everyone logs in as the same user)?

If its enough with a single user (that everyone uses) I think the only change you need to do is create like
username:common_user
email: info@company.x.x
password: company password

and then in the html form where you submit the login you just add to post hidden username=common_user & info@company.x.x

So the only visible field in the login form is the password (user and email is beeing submitted automatically... the advantage beeing all other login code is intact so if they change their minds they can just edit the login form and submit username or email if they want other users.

The drawback is everyone use the same pw and you cannot see who did what..

Re: PHP Login System

Posted: Tue Mar 25, 2014 1:09 am
by OpenSourceFan
Celauran wrote:Ah yes, of course. I had only looked at the code in your most recent post and hadn't gone back to look at the original.

Code: Select all

if (isset($_POST['password']) && !empty($_POST['password'])) {
//Connect to the database through our include
include_once "connect_to_mysql.php";
$password = ereg_replace("[^A-Za-z0-9]", "", $_POST['password']); // filter everything but numbers and letters
$password = md5($password);
...etc
Note that both restricting which characters can be contained within a password and using md5 to hash said password are pretty bad practices. I've left that bit alone because I don't want to break your existing login system, but it's something worth keeping in mind going forward.
I will keep that in mind when I create a system from scratch, something I wish to accomplish but is a long ways off.

This change worked as desired. At the moment, it only works as a glorified redirect, but that is due to the new .php page I created. I will attempt to accomplish this on my own for now, but is very likely that I will be back here shortly. :lol:
hybris wrote:Do you want different users (each one with their own password) or is it enough to have 1 user with a company pw (everyone logs in as the same user)?

If its enough with a single user (that everyone uses) I think the only change you need to do is create like
username:common_user
email: info@company.x.x
password: company password

and then in the html form where you submit the login you just add to post hidden username=common_user & info@company.x.x

So the only visible field in the login form is the password (user and email is beeing submitted automatically... the advantage beeing all other login code is intact so if they change their minds they can just edit the login form and submit username or email if they want other users.

The drawback is everyone use the same pw and you cannot see who did what..
I want different users with their own individual passwords. Or rather, that's what I have been instructed to do.

If I were creating my own system for my own use, I would just create a standard email + password system... though it is good to know that I have some options.

Re: PHP Login System

Posted: Thu Mar 27, 2014 6:17 pm
by OpenSourceFan
So as expected, I was unable to get the page to which my login system redirects to properly display.

Code: Select all

<?php
session_start(); // Must start session first thing
/* 
Created By Adam Khoury @ http://www.flashbuilding.com 
-----------------------June 20, 2008----------------------- 
*/
// See if they are a logged in member by checking Session data
$toplinks = "";
if (isset($_SESSION['id'])) {
	// Put stored session variables into local php variable
    $userid = $_SESSION['id'];
    $username = $_SESSION['username'];
	$toplinks = '<a href="member_profile.php?id=' . $userid . '">' . $username . '</a> &bull; 
	<a href="member_account.php">Account</a> &bull; 
	<a href="logout.php">Log Out</a>';
} else {
	$toplinks = '<a href="join_form.php">Register</a> &bull; <a href="login.php">Login</a>';
}
?>
<?php
// Use the URL 'id' variable to set who we want to query info about
$id = ereg_replace("[^0-9]", "", $_GET['id']); // filter everything but numbers for security
if ($id == "") {
	echo "Missing Data to Run";
	exit();
}
//Connect to the database through our include 
include_once "connect_to_mysql.php";
// Query member data from the database and ready it for display
$sql = mysql_query("SELECT * FROM members WHERE id='$id' LIMIT 1");
$count = mysql_num_rows($sql);
if ($count > 1) {
	echo "There is no user with that id here.";
	exit();	
}
while($row = mysql_fetch_array($sql)){
$country = $row["country"];
$state = $row["state"];
$city = $row["city"];
$accounttype = $row["accounttype"];
$bio = $row["bio"];
// Convert the sign up date to be more readable by humans
$signupdate = strftime("%b %d, %Y", strtotime($row['signupdate']));
}
?>
HTML STUFF
<div><?php echo $toplinks; ?></div>
OTHER HTML STUFF
Each time I log in, I get the message: Missing Data to Run. I can see that this is the fail message, but otherwise I'm still confused.

Incidentally, the .php page that the login system redirects to is not called "member_profile.php." I did try changing the page name in the code, but nothing happened.

Any advice? My apologies for double posting.

Re: PHP Login System

Posted: Thu Mar 27, 2014 6:57 pm
by Celauran
What that tells us is that either $_GET['id'] is not set or does not contain numbers.

Re: PHP Login System

Posted: Fri Mar 28, 2014 2:00 am
by OpenSourceFan
id in the MySQL server is an int type. Does that matter at all? It's what the tutorial suggested.

Re: PHP Login System

Posted: Fri Mar 28, 2014 7:22 am
by Celauran
I prefer to use UUIDs as my primary keys to avoid potential collisions if you have to merge databases, but that's beside the point. Your script is expecting a numerical ID parameter be passed to it (i.e. www.yoursite.com/somepage.php?id=237) and it's either receiving one that isn't numerical, or it isn't receiving one at all. You'll want to double check what's going on prior to the user arriving here. If they're being redirected from a login script, you'll need to ensure the redirect includes an ID to use on this page or allow for none to be set, in which case you present a form rather than a result set.

Re: PHP Login System

Posted: Sat Mar 29, 2014 11:07 pm
by OpenSourceFan
Found the issue, surprisingly.

Code: Select all

eader("location: member_profile.php?id=$id"); 
When I change that address, I left out ?id=$id. By putting it back in, the data was made available.

Re: PHP Login System

Posted: Sun Apr 06, 2014 5:13 pm
by OpenSourceFan
So now that my log in system works, there is one thing I need to make the overall system complete.

These log in system has three types of accounts. I need the page to which header(); redirects to display the data of a specific MySQL table. As in, account a shows table a, account b shows table b, and account c shows tables a, b, and the members account.

How do I go about doing this? I've thought of a few things that I will need to do in order to get a result.

1)

The existing login system uses

Code: Select all

include_once "connect_to_mysql.php";
In order to connect to the database and the "members" table in the first place. How would I access additional tables? Do I need to edit connect_to_mysql.php or can I command the webpage to access them as I need to?

2)

How do I specify to retrieve a specific table for a specific account type?

3)

I found some code that could be appropriate for displaying the data once the table is accessed.

{
echo "<tr>";

echo "<td>$row[0]</td>";
echo "<td>$row[1]</td>";

echo "</tr>\n";
}

Will this work?

As always, I appreciate your help in this regard. The login system already works as intend.

4)

Do I put all this php code inside my html body or outside?