PHP Login System

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: PHP Login System

Post by Celauran »

connect_to_mysql.php probably does just that; connects to the database. You specify which table to retrieve data from in your individual queries.

Code: Select all

SELECT foo, bar FROM members WHERE whatever
3)

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

Code: Select all

{
echo "<tr>";

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

echo "</tr>\n";
}
Will this work?
That code by itself is almost meaningless. You're pulling the first and second items from an array; that's all we can infer.

Lastly, you should strive to keep your PHP and HTML separate as much as possible. Keep the business layer separate from the presentation layer. If you're just learning, though, and working with an existing codebase that's maybe a little on the spaghetti side, don't sweat it.
OpenSourceFan
Forum Newbie
Posts: 16
Joined: Mon Mar 17, 2014 10:07 pm

Re: PHP Login System

Post by OpenSourceFan »

I'll keep that last sentence in mind. I prefer things to be neat when possible.

Okay, new approach and therefore new question: I want to put the information into two php files and then have the page display one or the other with the include function. How do I tell page to use one file for one user account type and the other for another type?

Essentially, I have account_a.php and account_b.php, and when user type a logs in, they see the contents of account_a.php in the body of the page and visa versa.
OpenSourceFan
Forum Newbie
Posts: 16
Joined: Mon Mar 17, 2014 10:07 pm

Re: PHP Login System

Post by OpenSourceFan »

I noticed that the login system has the following code on the page I need to display my data:

Code: Select all

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']));
}
Would the following work? (As in, is my syntax correct?)

Code: Select all

if($accounttype = "a"){include "account_a.php";}
Again, thank you everyone for your help!

EDIT:

I tried it for myself and it works except for one problem: Account Type C gets the same info as Account Type A.

Here is the updated code, which includes my attempt to have the three different account types and corresponding php pages (but still doesn't produce the desired effect).

Code: Select all

<?php
session_start();
$toplinks = "";
if (isset($_SESSION['id'])) {
	// Put stored session variables into local php variable
    $userid = $_SESSION['id'];
    $username = $_SESSION['username'];
	$toplinks = ' 
	<a href="logout.php">Click Here To Log Out</a>';
} else {
	$toplinks = '<a href="join_form.php">Register</a> &bull; <a href="login.php">Login</a>';
}
?>
<?php
$id = ereg_replace("[^0-9]", "", $_GET['id']); // filter everything but numbers for security
if ($id == "") {
	echo "Missing Data to Run";
	exit();
}
include_once "connect_to_mysql.php";
$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"];
$signupdate = strftime("%b %d, %Y", strtotime($row['signupdate']));

if($accounttype = "a"){include "account_a.php";}
elseif($accounttype = "b"){include "account_b.php";}
elseif($accounttype = "c"){include "account_c.php";}
else{echo "You done goofed.";}
}
?>
What am I missing here?
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: PHP Login System

Post by Celauran »

At the very least, you'd need to use a comparison operator (==) instead of assignment (=). Otherwise, yes, it should work.
OpenSourceFan
Forum Newbie
Posts: 16
Joined: Mon Mar 17, 2014 10:07 pm

Re: PHP Login System

Post by OpenSourceFan »

And you've fixed it! Everything works exactly as it should!

I know I keep saying this a lot, but thank you so very much for all your help! My boss will be very pleased, and I've learned a lot about PHP from this. Cheers!
OpenSourceFan
Forum Newbie
Posts: 16
Joined: Mon Mar 17, 2014 10:07 pm

Re: PHP Login System

Post by OpenSourceFan »

So one mild issue has come up.

The membership registration form that was included requires that a city and state are included, and my boss has no need of that so he wants that removed. I tried on my own but to no affect. Which parts of the code are the offender here?

Code: Select all

<?php
/* 
Created By Adam Khoury @ www.flashbuilding.com 
-----------------------June 20, 2008----------------------- 
*/
// Set error message as blank upon arrival to page
$errorMsg = "";
// First we check to see if the form has been submitted 
if (isset($_POST['username'])){
	//Connect to the database through our include 
	include_once "connect_to_mysql.php";
	// Filter the posted variables
	$username = ereg_replace("[^A-Za-z0-9]", "", $_POST['username']); // filter everything but numbers and letters
	$country = ereg_replace("[^A-Z a-z0-9]", "", $_POST['country']); // filter everything but spaces, numbers, and letters
	$state = ereg_replace("[^A-Z a-z0-9]", "", $_POST['state']); // filter everything but spaces, numbers, and letters
	$city = ereg_replace("[^A-Z a-z0-9]", "", $_POST['city']); // filter everything but spaces, numbers, and letters
	$accounttype = ereg_replace("[^a-z]", "", $_POST['accounttype']); // filter everything but lowercase letters
	$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
	// Check to see if the user filled all fields with
	// the "Required"(*) symbol next to them in the join form
	// and print out to them what they have forgotten to put in
	if((!$username) || (!$country) || (!$state) || (!$city) || (!$accounttype) || (!$email) || (!$password)){
		
		$errorMsg = "You did not submit the following required information!<br /><br />";
		if(!$username){
			$errorMsg .= "--- User Name";
		} else if(!$country){
			$errorMsg .= "--- Country"; 
		} else if(!$state){ 
		    $errorMsg .= "--- State"; 
	   } else if(!$city){ 
	       $errorMsg .= "--- City"; 
	   } else if(!$accounttype){ 
	       $errorMsg .= "--- Account Type"; 
	   } else if(!$email){ 
	       $errorMsg .= "--- Email Address"; 
	   } else if(!$password){ 
	       $errorMsg .= "--- Password"; 
	   }
	} else {
	// Database duplicate Fields Check
	$sql_username_check = mysql_query("SELECT id FROM members WHERE username='$username' LIMIT 1");
	$sql_email_check = mysql_query("SELECT id FROM members WHERE email='$email' LIMIT 1");
	$username_check = mysql_num_rows($sql_username_check);
	$email_check = mysql_num_rows($sql_email_check); 
	if ($username_check > 0){ 
		$errorMsg = "<u>ERROR:</u><br />Your User Name is already in use inside our system. Please try another.";
	} else if ($email_check > 0){ 
		$errorMsg = "<u>ERROR:</u><br />Your Email address is already in use inside our system. Please try another.";
	} else {
		// Add MD5 Hash to the password variable
       $hashedPass = md5($password); 
		// Add user info into the database table, claim your fields then values 
		$sql = mysql_query("INSERT INTO members (username, country, state, city, accounttype, email, password, signupdate) 
		VALUES('$username','$country','$state','$city','$accounttype','$email','$hashedPass', now())") or die (mysql_error());
		// Get the inserted ID here to use in the activation email
		$id = mysql_insert_id();
		// Create directory(folder) to hold each user files(pics, MP3s, etc.) 
		mkdir("memberFiles/$id", 0755); 
		// Start assembly of Email Member the activation link
		$to = "$email";
		// Change this to your site admin email
		$from = "admin@somewebsite.com";
		$subject = "Complete your registration";
		//Begin HTML Email Message where you need to change the activation URL inside
		$message = '<html>
		<body bgcolor="#FFFFFF">
		Hi ' . $username . ',
		<br /><br />
		You must complete this step to activate your account with us.
		<br /><br />
		Please click here to activate now >>
		<a href="http://www.somewebsite.com/activation.php?id=' . $id . '">
		ACTIVATE NOW</a>
		<br /><br />
		Your Login Data is as follows: 
		<br /><br />
		E-mail Address: ' . $email . ' <br />
		Password: ' . $password . ' 
		<br /><br /> 
		Thanks! 
		</body>
		</html>';
		// end of message
		$headers = "From: $from\r\n";
		$headers .= "Content-type: text/html\r\n";
		$to = "$to";
		// Finally send the activation email to the member
		mail($to, $subject, $message, $headers);
		// Then print a message to the browser for the joiner 
		print "<br /><br /><br /><h4>OK $firstname, one last step to verify your email identity:</h4><br />
		We just sent an Activation link to: $email<br /><br />
		<strong><font color=\"#990000\">Please check your email inbox in a moment</font></strong> to click on the Activation <br />
		Link inside the message. After email activation you can log in.";
		exit(); // Exit so the form and page does not display, just this success message
	} // Close else after database duplicate field value checks
  } // Close else after missing vars check
} //Close if $_POST
?>
<!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=iso-8859-1" />
<title>Member Registration</title>
</head>
<body>
<table width="600" align="center" cellpadding="4">
  <tr>
    <td width="7%">REGISTER A MEMBER HERE </td>
  </tr>
</table>
<table width="600" align="center" cellpadding="5">
  <form action="join_form.php" method="post" enctype="multipart/form-data">
    <tr>
      <td colspan="2"><font color="#FF0000"><?php echo "$errorMsg"; ?></font></td>
    </tr>
    <tr>
      <td width="163"><div align="right">User Name:</div></td>
      <td width="409"><input name="username" type="text" value="<?php echo "$username"; ?>" /></td>
    </tr>
    <tr>
      <td><div align="right">Country:</div></td>
      <td><select name="country">
      <option value="<?php echo "$country"; ?>"><?php echo "$country"; ?></option>
      <option value="Australia">Australia</option>
      <option value="Canada">Canada</option>
      <option value="France">France</option>
      <option value="Mexico">Mexico</option>
      <option value="New Zealand">New Zealand</option>
      <option value="United Kingdom">United Kingdom</option>
      <option selected="selected" value="United States">United States</option>
      <option value="Zimbabwe">Zimbabwe</option>
      </select></td>
    </tr>
    <tr>
      <td><div align="right">State: </div></td>
      <td><input name="state" type="text" value="<?php echo "$state"; ?>" /></td>
    </tr>
    <tr>
      <td><div align="right">City: </div></td>
      <td>
        <input name="city" type="text" value="<?php echo "$city"; ?>" />
      </td>
    </tr>
    <tr>
      <td><div align="right">Account Type: </div></td>
      <td><select name="accounttype">
        <option value="<?php echo "$accounttype"; ?>"><?php echo "$accounttype"; ?></option>
        <option selected="selected" value="a">Plan A</option>
        <option value="b">Plan B</option>
        <option value="c">Administrator Account</option>
      </select></td>
    </tr>
    <tr>
      <td><div align="right">Email: </div></td>
      <td><input name="email" type="text" value="<?php echo "$email"; ?>" /></td>
    </tr>
    <tr>
      <td><div align="right"> Password: </div></td>
      <td><input name="password" type="password" value="<?php echo "$password"; ?>" /> 
      <font size="" color="#006600">(letters or numbers only, no spaces no symbols)</font></td>
    </tr>
    <!--<tr>
      <td><div align="right"> Captcha: </div></td>
      <td>Add Captcha Here for security</td>
    </tr>-->
    <tr>
      <td><div align="right"></div></td>
      <td><input type="submit" name="Submit" value="Submit Form" /></td>
    </tr>
  </form>
</table>
</body>
</html>
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: PHP Login System

Post by Celauran »

If city and state aren't required, let's start by removing their fields from the form. You can delete this whole bit here:

Code: Select all

    <tr>
      <td><div align="right">State: </div></td>
      <td><input name="state" type="text" value="<?php echo "$state"; ?>" /></td>
    </tr>
    <tr>
      <td><div align="right">City: </div></td>
      <td>
        <input name="city" type="text" value="<?php echo "$city"; ?>" />
      </td>
    </tr>
Now that the user is no longer being prompted for them, we need to remove the validation. We can remove this

Code: Select all

        $state = ereg_replace("[^A-Z a-z0-9]", "", $_POST['state']); // filter everything but spaces, numbers, and letters
        $city = ereg_replace("[^A-Z a-z0-9]", "", $_POST['city']); // filter everything but spaces, numbers, and letters
This block we'll need to trim down to remove city/state checks, so

Code: Select all

        if((!$username) || (!$country) || (!$state) || (!$city) || (!$accounttype) || (!$email) || (!$password)){
becomes

Code: Select all

        if((!$username) || (!$country) || (!$accounttype) || (!$email) || (!$password)){
And we'll want to remove the lines that generate the 'field required' errors, so delete

Code: Select all

                } else if(!$state){ 
                    $errorMsg .= "--- State"; 
           } else if(!$city){ 
               $errorMsg .= "--- City"; 
Finally, we want to remove the fields from the INSERT query, so

Code: Select all

                $sql = mysql_query("INSERT INTO members (username, country, accounttype, email, password, signupdate) 
                VALUES('$username','$country','$accounttype','$email','$hashedPass', now())") or die (mysql_error());
and that should do it.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: PHP Login System

Post by Celauran »

Final code should look like this

Code: Select all

<?php
/* 
Created By Adam Khoury @ www.flashbuilding.com 
-----------------------June 20, 2008----------------------- 
*/
// Set error message as blank upon arrival to page
$errorMsg = "";
// First we check to see if the form has been submitted 
if (isset($_POST['username'])){
        //Connect to the database through our include 
        include_once "connect_to_mysql.php";
        // Filter the posted variables
        $username = ereg_replace("[^A-Za-z0-9]", "", $_POST['username']); // filter everything but numbers and letters
        $country = ereg_replace("[^A-Z a-z0-9]", "", $_POST['country']); // filter everything but spaces, numbers, and letters
        $accounttype = ereg_replace("[^a-z]", "", $_POST['accounttype']); // filter everything but lowercase letters
        $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
        // Check to see if the user filled all fields with
        // the "Required"(*) symbol next to them in the join form
        // and print out to them what they have forgotten to put in
        if((!$username) || (!$country) || (!$accounttype) || (!$email) || (!$password)){
                
                $errorMsg = "You did not submit the following required information!<br /><br />";
                if(!$username){
                        $errorMsg .= "--- User Name";
                } else if(!$country){
                        $errorMsg .= "--- Country"; 
           } else if(!$accounttype){ 
               $errorMsg .= "--- Account Type"; 
           } else if(!$email){ 
               $errorMsg .= "--- Email Address"; 
           } else if(!$password){ 
               $errorMsg .= "--- Password"; 
           }
        } else {
        // Database duplicate Fields Check
        $sql_username_check = mysql_query("SELECT id FROM members WHERE username='$username' LIMIT 1");
        $sql_email_check = mysql_query("SELECT id FROM members WHERE email='$email' LIMIT 1");
        $username_check = mysql_num_rows($sql_username_check);
        $email_check = mysql_num_rows($sql_email_check); 
        if ($username_check > 0){ 
                $errorMsg = "<u>ERROR:</u><br />Your User Name is already in use inside our system. Please try another.";
        } else if ($email_check > 0){ 
                $errorMsg = "<u>ERROR:</u><br />Your Email address is already in use inside our system. Please try another.";
        } else {
                // Add MD5 Hash to the password variable
       $hashedPass = md5($password); 
                // Add user info into the database table, claim your fields then values 
                $sql = mysql_query("INSERT INTO members (username, country, accounttype, email, password, signupdate) 
                VALUES('$username','$country','$accounttype','$email','$hashedPass', now())") or die (mysql_error());
                // Get the inserted ID here to use in the activation email
                $id = mysql_insert_id();
                // Create directory(folder) to hold each user files(pics, MP3s, etc.) 
                mkdir("memberFiles/$id", 0755); 
                // Start assembly of Email Member the activation link
                $to = "$email";
                // Change this to your site admin email
                $from = "admin@somewebsite.com";
                $subject = "Complete your registration";
                //Begin HTML Email Message where you need to change the activation URL inside
                $message = '<html>
                <body bgcolor="#FFFFFF">
                Hi ' . $username . ',
                <br /><br />
                You must complete this step to activate your account with us.
                <br /><br />
                Please click here to activate now >>
                <a href="http://www.somewebsite.com/activation.php?id=' . $id . '">
                ACTIVATE NOW</a>
                <br /><br />
                Your Login Data is as follows: 
                <br /><br />
                E-mail Address: ' . $email . ' <br />
                Password: ' . $password . ' 
                <br /><br /> 
                Thanks! 
                </body>
                </html>';
                // end of message
                $headers = "From: $from\r\n";
                $headers .= "Content-type: text/html\r\n";
                $to = "$to";
                // Finally send the activation email to the member
                mail($to, $subject, $message, $headers);
                // Then print a message to the browser for the joiner 
                print "<br /><br /><br /><h4>OK $firstname, one last step to verify your email identity:</h4><br />
                We just sent an Activation link to: $email<br /><br />
                <strong><font color=\"#990000\">Please check your email inbox in a moment</font></strong> to click on the Activation <br />
                Link inside the message. After email activation you can log in.";
                exit(); // Exit so the form and page does not display, just this success message
        } // Close else after database duplicate field value checks
  } // Close else after missing vars check
} //Close if $_POST
?>
<!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=iso-8859-1" />
<title>Member Registration</title>
</head>
<body>
<table width="600" align="center" cellpadding="4">
  <tr>
    <td width="7%">REGISTER A MEMBER HERE </td>
  </tr>
</table>
<table width="600" align="center" cellpadding="5">
  <form action="join_form.php" method="post" enctype="multipart/form-data">
    <tr>
      <td colspan="2"><font color="#FF0000"><?php echo "$errorMsg"; ?></font></td>
    </tr>
    <tr>
      <td width="163"><div align="right">User Name:</div></td>
      <td width="409"><input name="username" type="text" value="<?php echo "$username"; ?>" /></td>
    </tr>
    <tr>
      <td><div align="right">Country:</div></td>
      <td><select name="country">
      <option value="<?php echo "$country"; ?>"><?php echo "$country"; ?></option>
      <option value="Australia">Australia</option>
      <option value="Canada">Canada</option>
      <option value="France">France</option>
      <option value="Mexico">Mexico</option>
      <option value="New Zealand">New Zealand</option>
      <option value="United Kingdom">United Kingdom</option>
      <option selected="selected" value="United States">United States</option>
      <option value="Zimbabwe">Zimbabwe</option>
      </select></td>
    </tr>
    <tr>
      <td><div align="right">Account Type: </div></td>
      <td><select name="accounttype">
        <option value="<?php echo "$accounttype"; ?>"><?php echo "$accounttype"; ?></option>
        <option selected="selected" value="a">Plan A</option>
        <option value="b">Plan B</option>
        <option value="c">Administrator Account</option>
      </select></td>
    </tr>
    <tr>
      <td><div align="right">Email: </div></td>
      <td><input name="email" type="text" value="<?php echo "$email"; ?>" /></td>
    </tr>
    <tr>
      <td><div align="right"> Password: </div></td>
      <td><input name="password" type="password" value="<?php echo "$password"; ?>" /> 
      <font size="" color="#006600">(letters or numbers only, no spaces no symbols)</font></td>
    </tr>
    <!--<tr>
      <td><div align="right"> Captcha: </div></td>
      <td>Add Captcha Here for security</td>
    </tr>-->
    <tr>
      <td><div align="right"></div></td>
      <td><input type="submit" name="Submit" value="Submit Form" /></td>
    </tr>
  </form>
</table>
</body>
</html>
OpenSourceFan
Forum Newbie
Posts: 16
Joined: Mon Mar 17, 2014 10:07 pm

Re: PHP Login System

Post by OpenSourceFan »

Hi, long time no see! Thought I left a thank you, but apparently I did not. So, thank you for the previous help.

Unfortunately, I am in need of some new help. The login system you helped me create/created for me works fine, but my boss decided he wanted something more. He wants a system where the customers can buy the products on a system of pages inside the login system. I figured that would be simple enough, but I have run into two problems:

1) I cannot get the additional pages beyond the place the login system redirects to to check for an account, so pretty much anyone with a link can see the pages. I can garble them up with

Code: Select all

http://www.showtimetack.com/controlbarsdealers.php?id=' . $id . '"
and so on, but all they have to do is type

Code: Select all

http://www.showtimetack.com/controlbarsdealers.php
and they're in.

The following is the php code on the main page that checks for $id. Whenever I add it to the other pages, it says "Missing Data to Run".

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="logout.php" style="font-size:36px;">Click Here To 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']));
}
?>
Do I need to create modified versions of this for the subpages? If I am not clear about what I am trying to say, please let me know.

2) The payment system my company uses is Coolcart.net. It uses HTML to take orders and redirect them to its payment processing system. So far, everything works about that with this system except for one thing: The link to redirect people back from Coolcart.net payment processing page to the ordering page they were on cannot work like this:

Code: Select all

http://www.showtimetack.com/controlbarsdealers.php?id=' . $id . '"
It simply does not send the user back. When I use controlbarsdealers.php without anything after that, however, it does work. How do I get them from Coolcart back seamlessly with the existing system?

The HTML used on the ordering page is:

Code: Select all

        <input type="hidden" value="http://www.showtimetack.com/controlbarsdealers.php?id=' . $id . '"" name="ReturnLink"></input>
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: PHP Login System

Post by Celauran »

It's looking for $_GET['id'], so any page that doesn't have ?id=foo is going to display that error. It's not a good approach. Once you've got the user authenticated, stick their ID in session data and check against that instead. As for the redirect URL, there's no reason it can't work with a GET parameter. Your last code snippet has an extra " after $id, plus it's not clear if that line is part of an echo statement or what.
OpenSourceFan
Forum Newbie
Posts: 16
Joined: Mon Mar 17, 2014 10:07 pm

Re: PHP Login System

Post by OpenSourceFan »

Celauran wrote:It's looking for $_GET['id'], so any page that doesn't have ?id=foo is going to display that error. It's not a good approach. Once you've got the user authenticated, stick their ID in session data and check against that instead. As for the redirect URL, there's no reason it can't work with a GET parameter. Your last code snippet has an extra " after $id, plus it's not clear if that line is part of an echo statement or what.
Sounds good! So would http://www.showtimetack.com/controlbarsdealers.php?id=' . $id . ' would become http://www.showtimetack.com/controlbars ... ?id="$_GET['id']" then?

Also, could you please show me how to have the subpages grab the ID in the session data? I know some of the code from my previous post might help, but beyond that....
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: PHP Login System

Post by Celauran »

Not quite. Parameters passed in via URL (ie. key/value pairs after ?) are accessible via the $_GET super global. Given www.example.com/?id=123, $_GET['id'] will be 123.

As for storing things in session data, you'll basically want to add key/value pairs to the $_SESSION super global. Once your user has been authenticated, simply

Code: Select all

$_SESSION['user_id'] = $user_id;
or something to that effect. On sub-pages, after session_start(), simply check if $_SESSION['user_id'] is set and redirect them to the login page if it isn't. That's the gist of it, anyway.
OpenSourceFan
Forum Newbie
Posts: 16
Joined: Mon Mar 17, 2014 10:07 pm

Re: PHP Login System

Post by OpenSourceFan »

Celauran wrote:Not quite. Parameters passed in via URL (ie. key/value pairs after ?) are accessible via the $_GET super global. Given http://www.example.com/?id=123, $_GET['id'] will be 123.

As for storing things in session data, you'll basically want to add key/value pairs to the $_SESSION super global. Once your user has been authenticated, simply

Code: Select all

$_SESSION['user_id'] = $user_id;
or something to that effect. On sub-pages, after session_start(), simply check if $_SESSION['user_id'] is set and redirect them to the login page if it isn't. That's the gist of it, anyway.
So in regards to storing the data in the session, would it be on the main page? As in:

Code: Select all

<?php
session_start();
$_SESSION['id'] = $id;
$toplinks = "";
if (isset($_SESSION['id'])) {
        // Put stored session variables into local php variable
    $userid = $_SESSION['id'];
    $username = $_SESSION['username'];
        $toplinks = ' 
        <a href="logout.php" style="font-size:36px;">Click Here To 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']));
}
?>
What do I write for the subpages? I'm at a loss.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: PHP Login System

Post by Celauran »

No, you're trying to assign the value of $id to $_SESSION before $id is defined.

Code: Select all

<?php

session_start();

// If we don't have their user ID saved, redirect to login page.
if (!isset($_SESSION['user_id'])) {
	header("Location: login.php");
	exit;
}
As for setting $_SESSION['user_id'], you'd do that after a successful login.
OpenSourceFan
Forum Newbie
Posts: 16
Joined: Mon Mar 17, 2014 10:07 pm

Re: PHP Login System

Post by OpenSourceFan »

Celauran wrote:No, you're trying to assign the value of $id to $_SESSION before $id is defined.

Code: Select all

<?php

session_start();

// If we don't have their user ID saved, redirect to login page.
if (!isset($_SESSION['user_id'])) {
	header("Location: login.php");
	exit;
}
As for setting $_SESSION['user_id'], you'd do that after a successful login.
Doesn't

Code: Select all

if (isset($_SESSION['id'])) {
        // Put stored session variables into local php variable
    $userid = $_SESSION['id'];
    $username = $_SESSION['username'];
        $toplinks = ' 
        <a href="logout.php" style="font-size:36px;">Click Here To Log Out</a>';
} else {
        $toplinks = '<a href="join_form.php">Register</a> &bull; <a href="login.php">Login</a>';
}
already do that?

And how do I check for that variable with the subpages? I did go to W3Schools.com to try and figure that out, but I'm still not figuring it out.
Post Reply