Web Design and Programming Pt 22

PHP SecurityIn this part of my PHP video tutorial, I’ll walk you step-by-step through the process of:

  • Verifying your users identity from page to page
  • Dynamically updating links based on the login status of your user
  • Destroying Sessions and Cookies
  • Creating a logout page

If you haven’t, check out the article previous to this on How to Create a PHP Login Script. All of the code follows the video. Use it however you would like.

Code From the Video

Index.php Code

<?php
// Initialize a session.
session_start();
require_once(“./includes/confighamdb.php”);
?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en” xml:lang=”en”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″ />
<title>You Logged In</title>
</head>
<body>
<div id=”main”>
<?php
echo ‘<h1>Welcome’;
if (isset($_SESSION[‘first_name’])) {
$sql = “SELECT tokenid from users where userid = ‘$_SESSION[userid]'”;
$result = mysql_query($sql) or trigger_error(“You’re not logged in”);
if (mysql_affected_rows() == 1) { // A match was made.
$row = mysql_fetch_array ($result, MYSQL_NUM);
mysql_free_result($result);
mysql_close(); // Close the database connection.
if($_SESSION[‘token_id’] == $row[0])
{
echo “, {$_SESSION[‘first_name’]}!”;
$loggedin = 1;
}
else {
echo “, You’re not logged in”;
$loggedin = 0;
}
}
}
echo ‘</h1>’;
// Display links based upon the login status
if (isset($_SESSION[‘userid’]) AND (substr($_SERVER[‘PHP_SELF’] AND $loggedin, -10) != ‘logout.php’)) {
echo ‘<a href=”logout.php”>Logout</a><br />
<a href=”change_password.php”>Change Password</a><br />’;
} else { //  Not logged in.
echo ‘ <a href=”register.php”>Register</a><br />
<a href=”login.php”>Login to your account</a><br />
<a href=”forgot_password.php”>Forgot Password</a><br />’;
}
?>
</div>
</body>
</html>

Logout.php Code

<?php

// Initialize a session.

session_start();

require_once(“./includes/confighamdb.php”);

?>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en” xml:lang=”en”>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″ />

<title>Logout</title>

</head>

<body>

<div id=”main”>

<?php

// If no first_name variable exists, redirect the user.

if (!isset($_SESSION[‘first_name’])) {

header(“Location: http://localhost/login/index.php”);

exit(); // Quit the script.

} else { // Logout the user.

$_SESSION = array(); // Destroy the variables.

session_destroy(); // Destroy the session itself.

setcookie (session_name(), ”, time()-300, ‘/’, ”, 0); // Destroy the cookie.

}

// Print a customized message.

echo “<h3>You are now logged out.</h3>”;

?>

</div>

</body>

</html>

18 Responses to “Web Design and Programming Pt 22”

  1. Bill says:

    I have been studying your login scripts, and seem to be missing the change_password.php portion.

    I found a link in one of your comments that provided what I thought was the entire code, but still no change_password.

    Can you point me to the tutorial I missed?

    • admin says:

      In part 23 of the web design and programming tutorial I create a forgotten password script. You can also download all of the code in a zipped archive on this page http://www.newthinktank.com/videos/web-programming/php-mysql/

      I hope that helps

      • Bill says:

        I have the zip. In the file goodlogin.php is a line that references logout.php and change_password.php.

        The logout.php file is in the zip, but not the change_password.php. What changes would I need to make to the forgot_password.php filie, or would changing the link in goodlogin.php from change to forgot be the way to go.

        • admin says:

          I emailed you the code. Sorry about the confusion. I later replaced change_password.php with forgot_password.php. It is more secure and provides the same service. Either way I emailed you the original code from change_password.php if you want to see it. Thanks

          • Bill says:

            Great. I am trying to walk through this and learn from what you have done.

            I am really glad I found your site. There is a great wealth of information here.

            • admin says:

              Thanks Bill 🙂 I’m glad you like it. Sorry it isn’t better organized. I never thought I’d get 300,000 views a month. I would have cleaned better if I’d known

  2. Bill says:

    New topic from me.

    In your code you have:
    $_SESSION[‘first_name’] = $row[1];
    $_SESSION[‘userid’] = $row[4];

    What is the significance of the $row[1] and $row[4] in the code?

    Does the order of my fields affect these numbers?

    • admin says:

      No they aren’t all that important. You can add additional data to the session, or use less. You’ll have to change your code like wise for everything to work

  3. Bill says:

    Thanks for your wonderful tutorials. I have learned a lot, following along, and then working through the code modifying it to fit my particular situation.

    I have done a search on your site, but have not found a tutorial on uploading files. I have found several OLD uploads on other websites, but they do not seem to work.

    Can you point me to an upload script?

    • admin says:

      It is very hard to securely allow people to upload files. If you do this make sure you place the upload in a temporary folder. Then change the name and never provide direct access to it. You can find out more in my php security series.

  4. Jr says:

    I have another question

    In my index.php file, where it checks if there is a user logged in, there is a problem.
    Your code checked for the session and wrote the first_name, and else it wrote “You’re not logged in”.
    I had to put it like this instead:

    if (mysql_affected_rows() == 1) {
    $row = mysql_fetch_array ($result, MYSQL_NUM);
    mysql_free_result($result);

    if($_SESSION[‘token_id’] == $row[0]) {
    echo “, You’re not logged in”;
    $loggedin = 1;
    }
    else {
    echo “, {$_SESSION[‘first_name’]}!”;
    $loggedin = 0;
    }
    }

    Is it okay if I switched them? Or is there a problem on the session linked to the other question I posted regarding the user_id or userid?

  5. Pradep says:

    Hi
    I have posted my query couple of times as I am not sure which is the exact place to put so that it will come to your notice. My apology for this..

    First of all I would like to thank you for the awesome work you have done. I really appreciate it. I downloaded the zip file with the php code but having little problem in figuring out how to proceed.
    I want the following activities to be done:
    Registration
    Activation
    Login
    Logout
    Forgot Password
    Change Password

    Can you please help me in telling all the php files associated for the above activities? including the include php files and the headers. Since the zip folder contains lot of php files I am getting little confused in finding the latest and appropriate php files which can solve my problem.

    Sorry for putting you into trouble.

    Expecting a reply soon!
    Thanks, Pradeep

    • admin says:

      I’ll see if I can try to organize them better. All of the code is included with each part of the tutorial and then in the archive. I guess I never meant for this to be more than a teaching tool. Sorry I have it so disorganized. Here is a zipped archive that you may not have?

  6. Pradeep says:

    I have this zipped archive. But there are lot of files which are confusing. If you can just upload all the files relevant to my requirement as I have discussed above, than that would be great.

    Thanks for your response.
    Expecting a quick reply.

  7. Bryan says:

    Working through this great set of tutorials. Odd problem. I got “everything” to work properly for the login download you put together. Today I come back and run it and im getting an error:
    Undefined variable: loggedin in …\wamp\www\Test\index.php

    Haven’t changed a thing in the table or the php pages. Im sure its something obvious, but any suggestions would be appreciated!

    • admin says:

      I have noticed many people have trouble getting WAMP and XAMPP to work consistently. I have no idea why. I always install Apache directly on an OS. For PCs I always create a separate partition and install Umbuntu instead of installing Apche on Windows. I do this only because I always use linux machines for hosting. Personal preference.

      The most common issue seems to be a problem with session management. I hope that helps

Leave a Reply

Your email address will not be published.

Google+