Part 4: Passwording individual entries

Originally posted by Michelle.

Please note: The Build-A-Blog series is an introduction to creating a simple blog script using PHP. These tutorials are meant to help you to learn PHP and MySQL and to use these to fetch and store data and display it on a web page. These tutorials should not be used ‘as is’ on a production website – especially if you are new to PHP and do not understand what you are doing. We would recommend that you try the B-A-B series on a safe, development environment – such as an offline installation of PHP and MySQL – so you can learn how everything works.

GWG and its staffers accept no responsibility for anything that may (or may not) happen to your site or server as a result of you using these tutorials – you do so AT YOUR OWN RISK.

Welcome back to the Build A Blog Tutorial. This is Part 4: Passwording Individual Entries.

In this tutorial I am going to show you how to add a column to your table that allows you to define each entry as either passworded or not passworded. Then we’re going to add a checkbox to the entry form so that you can toggle that attribute. Finally we’ll modify the entry display pages to require a password on protected entries.

First things first, let’s alter the database. We’re going to use a bit of code that is just like the file we wrote to create the table in the first place. The only difference is the sql query, which will be:

$sql = "ALTER TABLE `php_blog` ADD `password` TINYINT DEFAULT '0' NOT NULL";

Remember that our table is called php_blog. If yours is something different, you’ll need to change that.

So our whole file should look like this:

<?php

mysql_connect ('localhost', 'db_username', 'db_password') ;
mysql_select_db ('db_name');

$sql = "ALTER TABLE `php_blog` ADD `password` TINYINT DEFAULT '0' NOT NULL";

$result = mysql_query($sql) or print ("Can't add the column 'password' to the table 'php_blog' in the database.<br />" . $sql . "<br />" . mysql_error());

mysql_close();

if ($result != false) {
    echo "The column 'password' was successfully added to your table 'php_blog'";
}

?>

Don’t forget to put in your database, your username, and your password. Save this file as alter.php, upload to your server, and view it in your browser. Once you get the success message, delete the file.

NOTE: If you load the file more than once, you will get an error message. It only works the FIRST TIME.

Now let’s add that checkbox. Open your blog entry form and find this code:

<p><strong><label for="title">Title:</label></strong> <input type="text" name="title" id="title" size="40" /></p>

We’re going to add a checkbox called "password" beside this. It should look like this:

<p><strong><label for="password">Password protect?</label></strong> <input type="checkbox" name="password" id="password" value="1" /></p>

By default this checkbox will not be checked, and a value of 0 will be entered into your database, denoting a non-protected entry. But when you write an entry and check this box, it will enter a value of 1 into your database, and the entry will be marked for password protection.

Now, in order for this checkbox to do any good, we need to edit the code that inserts your entries into the database. Find this code:

$sql = "INSERT INTO php_blog (timestamp,title,entry) VALUES ('$timestamp','$title','$entry')";

Edit it to include the password field:

$sql = "INSERT INTO php_blog (timestamp,title,entry,password) VALUES ('$timestamp','$title','$entry','$password')";

The order is not important as long as the column name (“password”) is in the same position as the variable ($password). (For example, I have both in the last position.)

Then, find this part:

    $month = htmlspecialchars(strip_tags($_POST['month']));
    $date = htmlspecialchars(strip_tags($_POST['date']));
    $year = htmlspecialchars(strip_tags($_POST['year']));
    $time = htmlspecialchars(strip_tags($_POST['time']));
    $title = htmlspecialchars(strip_tags($_POST['title']));
    $entry = $_POST['entry'];

…and add this to the end:

    $password = htmlspecialchars(strip_tags($_POST['password']));

This is to stop nasty code from being inserted into your database by hackers. It is very important, so don’t leave it out.

Finally we will edit our display pages. This part may be last, but it is also the most complicated, so we’ll go slowly. Open your index page and find this code:

while($row = mysql_fetch_array($result)) {

    $date = date("l F d Y", $row['timestamp']);

    $title = stripslashes($row['title']);
    $entry = stripslashes($row['entry']);

    ?>
    <p><strong><?php echo $title; ?></strong><br /><br />

    <?php echo $entry; ?><br /><br />
    Posted on <?php echo $date; ?>
    <hr /></p>

    <?php

}

First, I want you to cut out the following from the code and paste it into a note or something to save it for later:

    ?>
    <p><strong><?php echo $title; ?></strong><br /><br />
    <?php echo $entry; ?><br /><br />

    Posted on <?php echo $date; ?>
    <hr /></p>

    <?php
}

Next, you need to add in the variable $password, and the variable $id. There is no need to strip the slashes on these variables (like we did with the $title and $entry ones) since no quotes should have been entered and therefore no escaping needed.

while($row = mysql_fetch_array($result)) {

    $date = date("l F d Y", $row['timestamp']);

    $title = stripslashes($row['title']);
    $entry = stripslashes($row['entry']);
    $password = $row['password'];
    $id = $row['id'];
 

Now we’re going to tell it that if $password equals 1, we want it to do something:

while($row = mysql_fetch_array($result)) {

    $date = date("l F d Y", $row['timestamp']);

    $title = stripslashes($row['title']);
    $entry = stripslashes($row['entry']);
    $password = $row['password'];
    $id = $row['id'];

    if ($password == 1) {

    }

So, what’s going to go between those brackets? First, let’s have it print the entry title:

while($row = mysql_fetch_array($result)) {

    $date = date("l F d Y", $row['timestamp']);

    $title = stripslashes($row['title']);
    $entry = stripslashes($row['entry']);
    $password = $row['password'];
    $id = $row['id'];

    if ($password == 1) {
        echo "<p><strong>" . $title . "</strong></p>";
    }

Then we’ll have it print a little note informing readers that this entry will be password protected:

while($row = mysql_fetch_array($result)) {

    $date = date("l F d Y", $row['timestamp']);

    $title = stripslashes($row['title']);
    $entry = stripslashes($row['entry']);
    $password = $row['password'];
    $id = $row['id'];

    if ($password == 1) {
        echo "<p><strong>" . $title . "</strong></p>";

        printf("This is a password protected entry. If you have a password, log in below.");
    }

And, a little form to let them log in. The form action needs to be the URL of this individual entry, so you’ll need to put that in. For the example we’ll assume that the individual entry page is journal.php?id=$id

while($row = mysql_fetch_array($result)) {

    $date = date("l F d Y", $row['timestamp']);

    $title = stripslashes($row['title']);
    $entry = stripslashes($row['entry']);
    $password = $row['password'];
    $id = $row['id'];

    if ($password == 1) {
        echo "<p><strong>" . $title . "</strong></p>";

        printf("<p>This is a password protected entry. If you have a password, log in below.</p>");

        printf("<form method=\"post\" action=\"journal.php?id=%s\"><p><strong><label for=\"username\">Username:</label></strong><br /><input type=\"text\" name=\"username\" id=\"username\" /></p><p><strong><label for=\"pass\">Password:</label></strong><br /><input type=\"password\" name=\"pass\" id=\"pass\" /></p><p><input type=\"submit\" name=\"submit\" id=\"submit\" value=\"submit\" /></p></form>",$id);
    }

And add in our horizontal rule:

while($row = mysql_fetch_array($result)) {

    $date = date("l F d Y", $row['timestamp']);

    $title = stripslashes($row['title']);
    $entry = stripslashes($row['entry']);
    $password = $row['password'];
    $id = $row['id'];

    if ($password == 1) {
        echo "<p><strong>" . $title . "</strong></p>";

        printf("<p>This is a password protected entry. If you have a password, log in below.</p>");

        printf("<form method=\"post\" action=\"journal.php?id=%s\"><p><strong><label for=\"username\">Username:</label></strong><br /><input type=\"text\" name=\"username\" id=\"username\" /></p><p><strong><label for=\"pass\">Password:</label></strong><br /><input type=\"password\" name=\"pass\" id=\"pass\" /></p><p><input type=\"submit\" name=\"submit\" id=\"submit\" value=\"submit\" /></p></form>",$id);
        print "<hr />";
    }

So, if $password equals 1, it will print the entry title, the little "protected entry" note, a login form, and our horizontal rule. For our else, let’s grab that code we saved and add it back in:

while($row = mysql_fetch_array($result)) {

    $date = date("l F d Y", $row['timestamp']);

    $title = stripslashes($row['title']);
    $entry = stripslashes($row['entry']);
    $password = $row['password'];
    $id = $row['id'];

    if ($password == 1) {
        echo "<p><strong>" . $title . "</strong></p>";

        printf("<p>This is a password protected entry. If you have a password, log in below.</p>");

        printf("<form method=\"post\" action=\"journal.php?id=%s\"><p><strong><label for=\"username\">Username:</label></strong><br /><input type=\"text\" name=\"username\" id=\"username\" /></p><p><strong><label for=\"pass\">Password:</label></strong><br /><input type=\"password\" name=\"pass\" id=\"pass\" /></p><p><input type=\"submit\" name=\"submit\" id=\"submit\" value=\"submit\" /></p></form>",$id);
        print "<hr />";
    }
    else { ?>

        <p><strong><?php echo $title; ?></strong><br /><br />
        <?php echo $entry; ?><br /><br />
        Posted on <?php echo $date; ?>

        <hr /></p>

        <?php
    }
}

There, now our index entry page is password enabled. But we’re not done. This means nothing unless we make some changes to the individual entry page, too. So open that file, and at the top define your username and password:

$my_username = "USERNAME";
$my_password = "PASSWORD";

Now find this code:

while($row = mysql_fetch_array($result)) {

    $date = date("l F d Y", $row['timestamp']);

    $title = stripslashes($row['title']);
    $entry = stripslashes($row['entry']);
    ?>

    <p><strong><?php echo $title; ?></strong><br /><br />
    <?php echo $entry; ?><br /><br />

    Posted on <?php echo $date; ?>

    <hr /></p>

    <?php
}

Once again, we’re going to add in the $password variable, cut out the print statements, and add in the if/else statement:

while($row = mysql_fetch_array($result)) {

    $date = date("l F d Y", $row['timestamp']);

    $title = stripslashes($row['title']);
    $entry = stripslashes($row['entry']);
    $password = $row['password'];

    if ($password == 1) {

    }
    else {

    }

Let’s construct the if part of that statement. First, we’re going to add another if statement in it, to determine if the correct username has been entered:

    if ($password == 1) {
        if (isset($_POST['username']) && $_POST['username'] == $my_username) {

        }
    }

If the correct username has been entered, let’s check if the correct password was entered, too:

    if ($password == 1) {
         if (isset($_POST['username']) && $_POST['username'] == $my_username) {
             if (isset($_POST['pass']) && $_POST['pass'] == $my_password) {

             }
         }
    }

If the correct username and password were entered, we’ll display the entry:

    if ($password == 1) {
         if (isset($_POST['username']) && $_POST['username'] == $my_username) {
             if (isset($_POST['pass']) && $_POST['pass'] == $my_password) {
                 ?>
                 <p><strong><?php echo $title; ?></strong><br /><br />

                 <?php echo $entry; ?><br /><br />
                 Posted on <?php echo $date; ?>
                 <hr /></p>

                 <?php
             }
         }
    }

But if the wrong password was entered:

    if ($password == 1) {
         if (isset($_POST['username']) && $_POST['username'] == $my_username) {
             if (isset($_POST['pass']) && $_POST['pass'] == $my_password) {
                 ?>

                 <p><strong><?php echo $title; ?></strong><br /><br />

                 <?php echo $entry; ?><br />>br />
                 Posted on <?php echo $date; ?></p>

                <?php
             }
             else { ?>
                 <p>Sorry, wrong password.</p>

                 <?php
             }
         }
    }

And if the wrong username (or no username, if they came straight to the individual entry page) has been entered, let’s give them the same login screen they saw on the index page:

    if ($password == 1) {
         if (isset($_POST['username']) && $_POST['username'] == $my_username) {
             if (isset($_POST['pass']) && $_POST['pass'] == $my_password) {
                 ?>
                 <p><strong><?php echo $title; ?></strong><br /><br />

                 <?php echo $entry; ?><br /><br />
                 Posted on <?php echo $date; ?>
                 <hr /></p>

                 <?php

             }
             else { ?>

                 <p>Sorry, wrong password.</p>

                 <?php
             }
         }
         else {
            echo "<p><strong>" . $title . "</strong></p>";

            printf("<p>This is a password protected entry. If you have a password, log in below.</p>");

            printf("<form method=\"post\" action=\"journal.php?id=%s\"><p><strong><label for=\"username\">Username:</label></strong><br /><input type=\"text\" name=\"username\" id=\"username\" /></p><p><strong><label for=\"pass\">Password:</label></strong><br /><input type=\"password\" name=\"pass\" id=\"pass\" /></p><p><input type=\"submit\" name=\"submit\" id=\"submit\" value=\"submit\" /></p></form>",$id);
            print "<hr /><br /><br />";
        }
    }

And, of course, if $password does not equal 1:

    if ($password == 1) {
         if (isset($_POST['username']) && $_POST['username'] == $my_username) {
             if (isset($_POST['pass']) && $_POST['pass'] == $my_password) {
                 ?>
                 <p><strong><?php echo $title; ?></strong><br /><br />

                 <?php echo $entry; ?><br /><br />
                 Posted on <?php echo $date; ?>
                 <hr /></p>

                 <?php

             }
             else { ?>

                 <p>Sorry, wrong password.</p>

                 <?php
             }
         }
         else {
            echo "<p><strong>" . $title . "</strong></p>";

            printf("<p>This is a password protected entry. If you have a password, log in below.</p>");

            printf("<form method=\"post\" action=\"journal.php?id=%s\"><p><strong><label for=\"username\">Username:</label></strong><br /><input type=\"text\" name=\"username\" id=\"username\" /></p><p><strong><label for=\"pass\">Password:</label></strong><br /><input type=\"password\" name=\"pass\" id=\"pass\" /></p><p><input type=\"submit\" name=\"submit\" id=\"submit\" value=\"submit\" /></p></form>",$id);
            print "<hr /><br /><br />";
        }
    }
    else { ?>

        <p><strong><?php echo $title; ?></strong><br /><br />
        <?php echo $entry; ?><br /><br />
        Posted on <?php echo $date; ?></p>

        <?php
    }

So, let’s look at what we did to that bit of code:

while($row = mysql_fetch_array($result)) {

    $date = date("l F d Y", $row['timestamp']);

    $title = stripslashes($row['title']);
    $entry = stripslashes($row['entry']);
    $password = $row['password'];

    if ($password == 1) {
         if (isset($_POST['username']) && $_POST['username'] == $my_username) {
             if (isset($_POST['pass']) && $_POST['pass'] == $my_password) {
                 ?>

                 <p><strong><?php echo $title; ?></strong><br /><br />
                 <?php echo $entry; ?><br /><br />
                 Posted on <?php echo $date; ?></p>

                <?php
             }
             else { ?>
                 <p>Sorry, wrong password.</p>

                 <?php
             }
         }
         else {
            echo "<p><strong>" . $title . "</strong></p>";

            printf("<p>This is a password protected entry. If you have a password, log in below.</p>");

            printf("<form method=\"post\" action=\"journal.php?id=%s\"><p><strong><label for=\"username\">Username:</label></strong><br /><input type=\"text\" name=\"username\" id=\"username\" /></p><p><strong><label for=\"pass\">Password:</label></strong><br /><input type=\"password\" name=\"pass\" id=\"pass\" /></p><p><input type=\"submit\" name=\"submit\" id=\"submit\" value=\"submit\" /></p></form>",$id);
            print "<hr /><br /><br />";
        }
    }
    else { ?>

        <p><strong><?php echo $title; ?></strong><br /><br />
        <?php echo $entry; ?><br /><br />
        Posted on <?php echo $date; ?></p>

        <?php
    }
}

Now your password protected blog entries should be secure!

Comments are closed.