Jump to content

Authenticate and Redirect using Object Oriented PhP - HOW????


dhahlen

Recommended Posts

I am taking a beginning course in PHP, just as I thought I was getting the hang of things, the course threw in some OPP. Granted I've never really touched programming before, this is all new to me. The course seems to go from basic to "I'm lost as hell" in about 2 seconds. That being said, the course requires this:

 

* Create an LoginBox object class with all of the functionality needed to authenticate a user and redirect to another page based on success or failure

* A possible list of properties could be Action, Title, ButtonText, SuccessRedirect, FailRedirect, etc

 

I've watched all the killerphp videos on OPP, so I have a VERY basic understanding of how objects/classes work. However, the course does not provide any guidance on authentication methods or anything related to user authentication via php.

 

I figure I'll have a form page, in that form it will have two fields (username, password). The password can be the same for all users, and the password field may not be required at all. Basically, you have to put in a username/pass that exists in the class/object and this will re-direct you to the main page. If you do not authenticate, it will re-direct you to another page.

 

So far, I'll be needing:

 

-Basic php form page with 2 fields and a button

-A class that contains all the methods for what the object will do

-A button (object), when clicked, references the class and performs necessary checks for authentication

 

Does this seem right?

 

In all honesty, I really don't have a clue where to begin. While I do find all of this interesting, I feel I'm in over my head -- at least at this point.

 

Any guidance would be GREATLY appreciated.

 

Thanks,

Darren

Link to comment
Share on other sites

I did a screencast series on building a PHP based login system (available in the KillerSites University under PHP > PHP Login - http://www.killersites.com/university) but unfortunately it's procedural rather than object oriented. Still, might come in handy.

 

Sounds to me like you'll need:

-- a file which will contain the code for your login object, probably with a couple functions... I'd suggest keeping it pretty simple.

 

-- Perhaps the functions could be:

-- generateForm() - would use a PHP include to create the login form.

-- processForm() - would handle processing the form after it has been submitted. Could compare the values entered in the form to the correct login values. If the password is correct, you could set a session variable (which could be checked to see if the user was logged in or not) and redirect the user (probably using 'header("Location: yourfile.php")' to a different file.

-- checkLogin() - would check if the user is currently logged in or not

 

-- a file for your form, which would include the form fields and the submit button (included within the generateForm() function. I prefer to keep my PHP code and my HTML as separate as possible (for more info on this, do a Google search for PHP MVC - model/view/controller) so that's why I put it in a separate file.

 

-- an file to create the login object

 

-- a file to redirect to if the user logs in successfully

 

Obviously, this would be extremely basic, but you could always expand it as you gain more experience/confidence. Additional features could include checking if both fields have been filled in, showing an error message if one of the fields isn't filled in or the values input aren't the correct username/password, a logout function, etc.

Link to comment
Share on other sites

Since I was bored and had some free time... Here's a rough code outline for you:

 

login.php - creates the php login object

<?php

include_once("login_class.php");
$login = new Login();

if (isset($_POST['submit'])) // this checks if the submit button has been clicked
{
       // if so, process the form
$login->processForm();
}
else
{
       // if the button hasn't been clicked, show the form
$login->generateForm();
}

?>

 

login_class.php - the code for the login object

<?php

class login
{
var $username = "admin";
var $password = "password";

function __construct() // constructor, PHP5 only
{
	// if you need to do anything when the object is first created, place that code here
}

function generateForm()
{
	include("form.php");
}

function processForm()
{
	echo "form processing...";

	// called when the form is submitted. You would use
	// $_POST[] to get the data from the form and compare it against the variables 
	// within this object (accessed using "$this->"). If they match, set a SESSION 
	// variable (if it is set, you know the user is logged in, if not, he's not) and 
	// redirect using 'header("location: yourfile.")'. If not, call the generateForm()
	// function and have the user re-enter their login details
}

function checkLogin($redirect)
{
	// would check if the correct $_SESSION variable is set. If so, user is valid
	// and can view the requested page. If not, redirect the user using the header()
	// function to whatever $redirect is set to

	if (!isset($_SESSION['loggedin']))
	{
		// redirect user
		header("location: " . $redirect);
	}
}
}

?>

 

form.php - the HTML form

<html>
<head>
<title>Login Example</title>
</head>
<body>
<form action="" method="post">
<!-- leaving the action attribute blank will cause the page to redirect to itself when the submit button is clicked -->
	<div>
		<label for="username">Username:</label>
		<input name="username" id="username" type="text">
		<br/>
		<label for="password">Password:</label>
		<input name="password" id="password" type="text">
		<br/>
		<input name="submit" value="Login" type="submit">

	</div>
</form>
</body>
</html>

 

loggedin.php - the file that the user will see if they log in. If they try to access the page without being logged in, the system should redirect them back to the login page

<?php

include_once("login_class.php");
$login = new Login();
$login->checkLogin('login.php');

?>

You're logged in!

Link to comment
Share on other sites

Thanks a crap ton. Going to try to implement this code with some modifications, may take me a bit of time (by this evening for sure, the school website is having issues so I can't access the ftp to upload data). Ideally I'd like to understand what I am doing as I add it in, otherwise this course was a waste of time :) Your comments in the code appear to explain the whole process, I greatly appreciate the help! I'll post results and link to the page when completed.

 

Thanks again!

Link to comment
Share on other sites

In the loggedin.php, where is the redirect variable specified?

 

function checkLogin($redirect)

{

// would check if the correct $_SESSION variable is set. If so, user is valid

// and can view the requested page. If not, redirect the user using the header()

// function to whatever $redirect is set to

 

if (!isset($_SESSION['loggedin']))

{

// redirect user

header("location: " . $redirect);

 

 

I'm assuming I should be replacing "location:" with the path to the page in which I'd like to redirect?

 

Also, does not seem to be logging in with username/pass, but the form seems to be in tact.

 

The page is very basic, but as I've mentioned, I'm entirely new to all of this, you can find the URL here"

 

http://cis166.estrellamountain.edu/DARUP97011/module8.php

 

Click the "login page" link on the nav bar to get to the form.

Link to comment
Share on other sites

Your question about $redirect:

This variable is set on the loggedin.php page: $login->checkLogin('login.php'); I set it up so that when the checkLogin function is called, if the user isn't authenticated correctly, they will be directed to whatever path is included within the ().

 

"Also, does not seem to be logging in with username/pass, but the form seems to be in tact."

You're linking the wrong page -- you need to be linking to login.php. If you look at the login.php code, that's what sets everything up, creating the login object, displaying the form, ect.

 

Do keep in mind that there is a bit of code that still needs to be written, so what I have provided is a partially incomplete solution.

Link to comment
Share on other sites

Thanks, yes, I will be working through it slowly. I figured I'd get your templates up and troubleshoot/ask questions as I work through all of them. Be aware that I'll probably get confused several times while attempting to figure all of this out, hah. It really is quite the learning process for me. Things tend to references other pages and bounce around quite a bit, so it's easy to get lost.

 

 

I initially had the link to login.php - I ended up changing it for some reason, I don't remember why =/

Link to comment
Share on other sites

No worries. Jumping right in to OOP is a big step if you don't already have a strong understanding of regular procedural PHP, so a bit of confusion is normal. However, being able to understand OOP will definitely help you in the long run.

 

In addition to the KillerSites tutorials (which it sounds like you've already done) you might want to check out http://net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/. It's one of the best beginner's articles I know for talking about OOP.

Link to comment
Share on other sites

No worries. Jumping right in to OOP is a big step if you don't already have a strong understanding of regular procedural PHP, so a bit of confusion is normal. However, being able to understand OOP will definitely help you in the long run.

 

In addition to the KillerSites tutorials (which it sounds like you've already done) you might want to check out http://net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/. It's one of the best beginner's articles I know for talking about OOP.

 

I was reading through that before I posted here :)

 

I've updated the page links accordingly. Seems to hang up on form processing...

 

Makes sense, because the function processForm() doesn't do anything (yet).

 

Now, when the processForm() function is called, I want to do the following:

 

if($_POST['username']=='admin' && $_POST['password']=='password')

$this->$username;

$this->$password;

 

Is this along the right track? I need to review the $this-> material

Link to comment
Share on other sites

Seems like you'd want to do

 

if($_POST['username']==$this->username && $_POST['password']==$this->password)

 

No extra "$" after the "->" and you'd want to compare the variables directly, rather than using 'admin' or 'password'.

 

But this should be referenced in a page other than the login_class.php page?

 

So far the function processForm() does the following:

 

-echo's "form processing.."

-verifies the username and password using $this to reference the username/password variable

 

function processForm()

{

echo "form processing...";

}

{

if($_POST['username']==$this->username && $_POST['password']==$this->password)

}

 

Now what to do with it afterward, I haven't used session variables. However, I don't think the form process function is complete.

Link to comment
Share on other sites

Getting closer:

 

function processForm()
{
   //echo "form processing..."; // you'd want to remove this line
   if($_POST['username']==$this->username && $_POST['password']==$this->password)
   {
       // set session variable
       // redirect user using header() function -- see checkLogin() function for example
   }
   else
   {
       // show the form using generateForm() function
   }
}

 

The only place you need to add this code to is within the login class. You'll notice the code for login.php:

 

<?php

include_once("login_class.php");
$login = new Login();

if (isset($_POST['submit'])) // this checks if the submit button has been clicked
{
       // if so, process the form
       $login->processForm();
}
else
{
       // if the button hasn't been clicked, show the form
       $login->generateForm();
}

?>

 

You'll notice that this code automatically calls the processForm() function if the submit button is pressed.

Link to comment
Share on other sites

Maybe my tools are limited.... I'm using textpad for code and the only thing I have to troubleshoot is the browser.

 

The isset command under checkLogin references a session name called "loggedin"

 

IN that case, I would have to set my session to generate a session titled "loggedin"

 

// Starts the Session

session_start();

 

// Gives the session a name?????

$_SESSION['login']="loggedin";

Link to comment
Share on other sites

<?php

class login
{
       var $username = "admin";
       var $password = "password";

       function __construct() // constructor, PHP5 only
       {
               // if you need to do anything when the object is first created, place that code here
       }

       function generateForm()
       {
               include("form.php");
       }

       function processForm()
       {

       		if($_POST['username']==$this->username && $_POST['password']==$this->password)
			{
				session_start();
				$_SESSION['login']="loggedin";
			}

					// set session variable
			        // redirect user using header() function -- see checkLogin() function for example
			else
			{
			        // show the form using generateForm() function
			        header("location: " . login.php);
			}
	}

       function checkLogin($redirect)
       {
               // would check if the correct $_SESSION variable is set. If so, user is valid
               // and can view the requested page. If not, redirect the user using the header()
               // function to whatever $redirect is set to

               if (!isset($_SESSION['loggedin']))
               {
                       // redirect user
                       header("location: " . module8.php);
               }
               else
               {
                		header("location: " . login.php);
               }
       }
}

?>

Link to comment
Share on other sites

If you are testing this code in a browser, you should be seeing error messages that will indicate where your errors are.

 

if($_POST['username']==$this->username && $_POST['password']==$this->password)
                               {
                                       session_start(); // probably best to move this to the first line after "<?php" in login.php
                                       //$_SESSION['login']="loggedin";
                                       $_SESSION['loggedin'] = TRUE;
                                       // then use header to redirect the user to the logged in page
                               }

                                               // set session variable
                                       // redirect user using header() function -- see checkLogin() function for example
                               else
                               {
                                       // show the form using generateForm() function
                                       // header("location: " . login.php);
                                       // no need to use header -- use the generateForm() function

                               }

Link to comment
Share on other sites

Well, the login portion works (great!) but it keeps failing when I try to call the generateForm function

 

I thought you could call a function by it's name.... see below

 

<?php

class login
{
       var $username = "admin";
       var $password = "password";

       function __construct() // constructor, PHP5 only
       {
               // if you need to do anything when the object is first created, place that code here
       }

       function generateForm()
       {
               include("form.php");
       }

       function processForm()
       {

       		if($_POST['username']==$this->username && $_POST['password']==$this->password)
			{
				$_SESSION['loggedin'] = TRUE;

                                       // inserted the header here rather than using isset below
                                       // if i remove the header line blow the page will not forward therefore 
                                       // something else is wrong with the code

				header("location: " . ' module8.' .'php ');
			}
			else
			{
			        // show the form using generateForm() function
                                       // this is also not working

			        generateForm();
			}
	}

       function checkLogin($redirect)
       {
               // would check if the correct $_SESSION variable is set. If so, user is valid
               // and can view the requested page. If not, redirect the user using the header()
               // function to whatever $redirect is set to

               if (!isset($_SESSION['loggedin']))
               {
                       // redirect user
                       header("location: " . module8.' .'php ');
               }
               else
               {
                               // Another call to the form which probably does not work 

                		generateForm();
               }
       }
}

?>

Link to comment
Share on other sites

Within the processForm() function:

"header("location: " . ' module8.' .'php ');"

There's no need to do this. I only used a . since I wanted to add a variable. Rather, use 'header("location: module8.php");'.

 

"generateForm();"

You need to use "$this->generateForm();" since the function you are calling is part of the object.

 

Within the checkLogin() function, there's no need to change that code. This will work just fine:

 

if (!isset($_SESSION['loggedin']))
{
   // redirect user if not logged in
   header("location: " . $redirect);
}

 

The checkLogin() functionality is only intended to check that the user is authorized to view the page. If not, it redirects them to whatever page you choose. If the user is logged in, nothing happens.

Link to comment
Share on other sites

It seems to be getting hung up somewhere, it generates the form if the user/pass is not correct, but it does not redirect.

 

Also, I do not understand the $redirect syntax

 

if the user is not logged in, it performs $redirect, but I do not see where this is defined?

 

If I end up putting the header("location: module8.php") under the $_SESSION['loggedin'] = TRUE, I know it's working.

 

Something is happening where the checkLogin function is not properly redirecting to the page

Link to comment
Share on other sites

It seems to be getting hung up somewhere, it generates the form if the user/pass is not correct, but it does not redirect.

My guess is that actually, yes, it is redirecting, but the checkLogin() functionality is kicking you out. Have you added "session_start();" to your files? You need to add it to the top of any files that use the session -- login.php and loggedin.php.

 

Also, I do not understand the $redirect syntax

 

So this is this is the way that the function is defined:

 

function checkLogin($redirect) 

 

and this is how you call the function (within loggedin.php):

 

$login->checkLogin('login.php');

 

The section of text within the () is passed into the checkLogin function. So when that code is called, 'login.php' is passed into the checkLogin function. Within that function, anytime the $redirect variable is used (for example, in header() ) it looks to see what value was passed in ("login.php").

Link to comment
Share on other sites

Even with the session_start(); located in login.php, loggedin.php, it still does not redirect.

 

I couldn't simplify it and set the else statement under the processForm to redirect to another page... but for the sake of understanding, I really want to know why it's not working.

 

How long does the session stay active? I know it's a browser session, so it's temporary.

 

Thanks for the info on that $redirect, it still confuses me how it checks a file within a file and then that file references another file, this is why I get lost, stuff is going on all over the place.

Link to comment
Share on other sites

Can you post all of the code you are using? I'm not sure what you called your files, but I'd need to see login.php, login_class.php, and loggedin.php. I shouldn't need to see the form, but you might post that anyway so I can test with the exact code you are using.

 

How long does the session stay active? I know it's a browser session, so it's temporary.

It stays active until the browser is closed, or the session is destroyed using PHP.

Link to comment
Share on other sites

login_class.php

 

<?php

class login
{
       var $username = "admin";
       var $password = "password";

       function __construct() // constructor, PHP5 only
       {
               // if you need to do anything when the object is first created, place that code here
       }

       function generateForm()
       {
               include("form.php");
       }

       function processForm()
       {

       		if($_POST['username']==$this->username && $_POST['password']==$this->password)
			{
				$_SESSION['loggedin'] = TRUE;
			}
			else
			{
			        // show the form using generateForm() function
			        $this->generateForm();
			}
	}

       function checkLogin($redirect)
       {
               // would check if the correct $_SESSION variable is set. If so, user is valid
               // and can view the requested page. If not, redirect the user using the header()
               // function to whatever $redirect is set to

               if (!isset($_SESSION['loggedin']))
               {
                       // redirect user
                       header("location: module8.php");
               }
               else
               {
                       // redirect if user is not logged in
                		header("location: " . $redirect);
               }
       }
}

?>

 

login.php

 

<html>

<head>


<style type="text/css">

/* Style Code referenced from http://www.webreference.com/programming/css_frames/index.html */

/* Below are the CSS styles which are referenced throughout the webpage */

body {
 margin:0;
 border:0;
 pading:0;
 height:100%;
 background:#eee;
 font-family:arial, verdana, sans-serif;
 font-size:76%;
 overflow: hidden;
 }

#header {
 position:absolute;
 top:0;
 left:0;
 width:100%;
 height:100px;
 overflow:auto;
 text-align:center;
 background:#53829d;
 color:#fff;
 }

#footer {
 position:absolute;
 bottom:0;
 left:0;
 width:100%;
 height:50px;
 overflow:auto;
 text-align:center; /* Aligns the footer text to the center */
 background:#73a2bd;
 }

#contents {
 position:fixed;
 top:100px; /* This allows the contents of the body to miss the header position */
 left:0;
 bottom:50px; /* This allows the contents of the body to miss the footer position */
 right:0;
 overflow:auto; /* Adds scroll bars if needed */
 background:#fff;
 }

/* navlist referenced from http://css.maxdesign.com.au/listamatic/horizontal01.htm */

#navlist li
 {
 display: inline;
 list-style-type: none;
 padding-right: 20px;
 }

/* Defines the width of the paragraphs */

 p {width:500px;}


/* for internet explorer */

* html body {
 padding:120px 0 50px 0;
 }

* html #contents {
 height:100%;
 width:100%;
 }

</style>

</head>

<body>

<div id="header">
<?php echo "<h1>Welcome to Darren's Website</h1>";?>
<?php echo "<h2>This line uses h2 style with php</h2>";?>
</div>

<div id="footer">
<h3>Test Footer using h3, aligned center</h3>
</div>

<div id="contents">
<div id="navcontainer">
<ul id="navlist">
	<li id="active"><a href="http://cis166.estrellamountain.edu/DARUP97011/module8.php" id="current">Home</a></li>
	<li><a href="guestbook.php">Guest Book</a></li>
	<li><a href="guestbookwrites.php">Guest Book Writes</a></li>
	<li><a href="mailto:DARUP97011@maricopa.edu">Contact Me</a></li>
	<li><a href="contents.txt">Page Code</a></li>
	<li><a href="mailform.php">E-mail Form</a></li>
	<li><a href="login.php">Login Page</a></li>
</ul>
</div>

<h1>Contents of the Body goes here, using h1 style</h1>
<p>
Today's Date is <?php echo date("m-d-Y");?>
<p>
<?php
session_start();
include_once("login_class.php");
$login = new Login();

if (isset($_POST['submit'])) // this checks if the submit button has been clicked
{
       // if so, process the form
       $login->processForm();
}
else
{
       // if the button hasn't been clicked, show the form
       $login->generateForm();
}

?>
<p>
</body>
</html>

 

loggedin.php

 

<html>

<head>


<style type="text/css">

/* Style Code referenced from http://www.webreference.com/programming/css_frames/index.html */

/* Below are the CSS styles which are referenced throughout the webpage */

body {
 margin:0;
 border:0;
 pading:0;
 height:100%;
 background:#eee;
 font-family:arial, verdana, sans-serif;
 font-size:76%;
 overflow: hidden;
 }

#header {
 position:absolute;
 top:0;
 left:0;
 width:100%;
 height:100px;
 overflow:auto;
 text-align:center;
 background:#53829d;
 color:#fff;
 }

#footer {
 position:absolute;
 bottom:0;
 left:0;
 width:100%;
 height:50px;
 overflow:auto;
 text-align:center; /* Aligns the footer text to the center */
 background:#73a2bd;
 }

#contents {
 position:fixed;
 top:100px; /* This allows the contents of the body to miss the header position */
 left:0;
 bottom:50px; /* This allows the contents of the body to miss the footer position */
 right:0;
 overflow:auto; /* Adds scroll bars if needed */
 background:#fff;
 }

/* navlist referenced from http://css.maxdesign.com.au/listamatic/horizontal01.htm */

#navlist li
 {
 display: inline;
 list-style-type: none;
 padding-right: 20px;
 }

/* Defines the width of the paragraphs */

 p {width:500px;}


/* for internet explorer */

* html body {
 padding:120px 0 50px 0;
 }

* html #contents {
 height:100%;
 width:100%;
 }

</style>

</head>

<body>

<div id="header">
<?php echo "<h1>Welcome to Darren's Website</h1>";?>
<?php echo "<h2>This line uses h2 style with php</h2>";?>
</div>

<div id="footer">
<h3>Test Footer using h3, aligned center</h3>
</div>

<div id="contents">
<div id="navcontainer">
<ul id="navlist">
	<li id="active"><a href="http://cis166.estrellamountain.edu/DARUP97011/module8.php" id="current">Home</a></li>
	<li><a href="guestbook.php">Guest Book</a></li>
	<li><a href="guestbookwrites.php">Guest Book Writes</a></li>
	<li><a href="mailto:DARUP97011@maricopa.edu">Contact Me</a></li>
	<li><a href="contents.txt">Page Code</a></li>
	<li><a href="mailform.php">E-mail Form</a></li>
	<li><a href="form.php">Login Page</a></li>
</ul>
</div>

<h1>Contents of the Body goes here, using h1 style</h1>
<p>
Today's Date is <?php echo date("m-d-Y");?>
<p>
This page uses a combination of html, php, and CSS. All styles are handled by CSS, as well as the navigation menu, header and footer. The page is
written in HTML, but is excuted on the server end using php. I have left examples as to what certain header and text formatting look like. The code will also
reference pages I have used. I've also provided links for them below.
</p>
<p>
<a href="http://css.maxdesign.com.au/listamatic/horizontal01.htm">Navigation Menu CSS Code referenced here</a>
<p>
<a href="http://www.webreference.com/programming/css_frames/index.html">CSS Styles referenced here</a>
<p>
<?php
session_start();
include_once("login_class.php");
$login = new Login();
$login->checkLogin('login.php');

?>

You're logged in!

</body>
</html>

 

form.php

 

<html>

<head>


<style type="text/css">

/* Style Code referenced from http://www.webreference.com/programming/css_frames/index.html */

/* Below are the CSS styles which are referenced throughout the webpage */

body {
 margin:0;
 border:0;
 pading:0;
 height:100%;
 background:#eee;
 font-family:arial, verdana, sans-serif;
 font-size:76%;
 overflow: hidden;
 }

#header {
 position:absolute;
 top:0;
 left:0;
 width:100%;
 height:100px;
 overflow:auto;
 text-align:center;
 background:#53829d;
 color:#fff;
 }

#footer {
 position:absolute;
 bottom:0;
 left:0;
 width:100%;
 height:50px;
 overflow:auto;
 text-align:center; /* Aligns the footer text to the center */
 background:#73a2bd;
 }

#contents {
 position:fixed;
 top:100px; /* This allows the contents of the body to miss the header position */
 left:0;
 bottom:50px; /* This allows the contents of the body to miss the footer position */
 right:0;
 overflow:auto; /* Adds scroll bars if needed */
 background:#fff;
 }

/* navlist referenced from http://css.maxdesign.com.au/listamatic/horizontal01.htm */

#navlist li
 {
 display: inline;
 list-style-type: none;
 padding-right: 20px;
 }

/* Defines the width of the paragraphs */

 p {width:500px;}


/* for internet explorer */

* html body {
 padding:120px 0 50px 0;
 }

* html #contents {
 height:100%;
 width:100%;
 }

</style>

</head>

<body>

<div id="header">
<?php echo "<h1>Welcome to Darren's Website</h1>";?>
<?php echo "<h2>This line uses h2 style with php</h2>";?>
</div>

<div id="footer">
<h3>Test Footer using h3, aligned center</h3>
</div>

<div id="contents">
<div id="navcontainer">
<ul id="navlist">
	<li id="active"><a href="http://cis166.estrellamountain.edu/DARUP97011/module8.php" id="current">Home</a></li>
	<li><a href="guestbook.php">Guest Book</a></li>
	<li><a href="guestbookwrites.php">Guest Book Writes</a></li>
	<li><a href="mailto:DARUP97011@maricopa.edu">Contact Me</a></li>
	<li><a href="contents.txt">Page Code</a></li>
	<li><a href="mailform.php">E-mail Form</a></li>
	<li><a href="login.php">Login Page</a></li>
</ul>
</div>

<h1>Contents of the Body goes here, using h1 style</h1>
<p>
Today's Date is <?php echo date("m-d-Y");?>
<p>
       <h2>Login Example</h2>
       <form action="" method="post">
       <!-- leaving the action attribute blank will cause the page to redirect to itself when the submit button is clicked -->
               <div>
                       <label for="username">Username:</label>
                       <input name="username" id="username" type="text">
                       <br/>
                       <label for="password">Password:</label>
                       <input name="password" id="password" type="text">
                       <br/>
                       <input name="submit" value="Login" type="submit">

               </div>
       </form>

</body>
</html>

Link to comment
Share on other sites

A couple things...

 

I didn't realize you were mixing HTML with the PHP code, which causes some minor problems.

 

-- first off, any time you use "session_start()" that needs to be the first line in the file. Using "session_start()" somewhere in the middle of the file after HTML code has already been output to the browser will cause errors. So in your loggedin.php file, move the PHP code block to the first line in the file and make sure there are no spaces or empty lines before the opening <?php:

 

<?php
session_start();
include_once("login_class.php");
$login = new Login();
$login->checkLogin('login.php');
?>

 

-- You don't need any html in your login.php form. All you need is the PHP. The $login->generateForm will create the form if necessary.

 

<?php
session_start();
include_once("login_class.php");
$login = new Login();

if (isset($_POST['submit'])) // this checks if the submit button has been clicked
{
       // if so, process the form
       $login->processForm();
}
else
{
       // if the button hasn't been clicked, show the form
       $login->generateForm();
}

?>

 

And in in your login_class.php, you've done some changes to the processForm() and checkLogin() functions that don't make a lot of sense to me. Here is the corrected code:

 

 function processForm()
       {

                       if($_POST['username']==$this->username && $_POST['password']==$this->password)
                               {
                                       $_SESSION['loggedin'] = TRUE;
                                       header("location: loggedin.php"); // added
                               }
                               else
                               {
                                       // show the form using generateForm() function
                                       $this->generateForm();
                               }
               }

       function checkLogin($redirect)
       {
               // would check if the correct $_SESSION variable is set. If so, user is valid
               // and can view the requested page. If not, redirect the user using the header()
               // function to whatever $redirect is set to

               if (!isset($_SESSION['loggedin']))
               {
                       // redirect if user is not logged in
                      header("location: " . $redirect); // changed
               }
               // removed an else statement
       }

Link to comment
Share on other sites

One other thing to note in case it hasn't been covered in your class... the "!" in "if (!isset($_SESSION['loggedin']))" indicates "NOT". So that line reads, if the session variable is NOT set, do something.

 

The only time you need to use the checkLogin() function is to make sure that someone who isn't authorized can't access a restricted page. Actually, perhaps a better name for that function would be "checkLoggedIn()" to help reduce confusion.

Link to comment
Share on other sites

Everything appears to be working, which now has me curious on the session_destroy() command

 

If we go to anywhere on the page, the session is active. If I click the login page again, can I make an option that says "Already Logged in, click here to log out" and then have the log out link perform a session_destroy() ?

 

This isn't a requirement, but it would be useful in a situation such as this. If someone is logged it and then went to the login page, in most real world scenarios it would tell you the user is already logged in. Also, I understand that we'd normally be authenticating against something like sql or database, versus the method we've completed here.

 

Thanks for all your help, I'm sure I'll be asking more questions as things progress.

Link to comment
Share on other sites

One other thing to note in case it hasn't been covered in your class... the "!" in "if (!isset($_SESSION['loggedin']))" indicates "NOT". So that line reads, if the session variable is NOT set, do something.

 

The only time you need to use the checkLogin() function is to make sure that someone who isn't authorized can't access a restricted page. Actually, perhaps a better name for that function would be "checkLoggedIn()" to help reduce confusion.

 

Ahh, good to know. Removing that ! would redirect a user if they were logged into the session, doing the opposite of what it does currently.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...