11.2. Adding Administrators in the Database

You have a place to store administrators; now you're ready to start creating them. Your first step is to create a form that allows you to enter a username and password in an HTML form. Once you accomplish this, you need to store the information in the database for later use.

11.2.1. Building an HTML Form

To build your HTML form, you need to write a new function, named createUserForm(). When called, this function returns a string of HTML that displays a form that asks for a username and password for the new admin.

You can add the code in bold to functions.inc.php to make the createUserForm() function:

function createUserForm()
{
    return <<<FORM
<form action="/simple_blog/inc/update.inc.php" method="post">
    <fieldset>
        <legend>Create a New Administrator</legend>
        <label>Username
            <input type="text" name="username" maxlength="75" />
        </label>
        <label>Password
            <input type="password" name="password" />
        </label>
        <input type="submit" name="submit" value="Create" />
        <input type="submit" name="submit" value="Cancel" />
        <input type="hidden" name="action" value="createuser" />
    </fieldset>
</form>
FORM;
}

Next, you need to add code to call this function if the user chooses to create a new admin. Use the http://localhost/simple_blog/admin/createuser URL as your call to create a new admin for your blog.

To make this URL call the createUserForm() function, you need to add an if block to admin.php that triggers when the $page variable you use to determine what page is being edited is set to createuser.

Next, modify admin.php with the code in bold to incorporate the new form into your blog:

<?php

    /*
     * Include the necessary files
     */

include_once 'inc/functions.inc.php';
    include_once 'inc/db.inc.php';

    // Open a database connection
    $db = new PDO(DB_INFO, DB_USER, DB_PASS);

    if(isset($_GET['page']))
    {
        $page = htmlentities(strip_tags($_GET['page']));
    }
    else
    {
        $page = 'blog';
    }

    if(isset($_POST['action']) && $_POST['action'] == 'delete')
    {
        if($_POST['submit'] == 'Yes')
        {
            $url = htmlentities(strip_tags($_POST['url']));
            if(deleteEntry($db, $url))
            {
                header("Location: /simple_blog/");
                exit;
            }
            else
            {
                exit("Error deleting the entry!");
            }
        }
        else
        {
            header("Location: /simple_blog/blog/$_POST[url]");
        }
    }

    if(isset($_GET['url']))
    {
        $url = htmlentities(strip_tags($_GET['url']));

        // Check if the entry should be deleted
        if($page == 'delete')
        {
            $confirm = confirmDelete($db, $url);
        }

// Set the legend of the form
        $legend = "Edit This Entry";

        $e = retrieveEntries($db, $page, $url);
        $id = $e['id'];
        $title = $e['title'];
        $img = $e['image'];
        $entry = $e['entry'];
    }
    else
    {
        // Check if we're creating a new user
        if($page == 'createuser')
        {
            $create = createUserForm();
        }

         // Set the legend
        $legend = "New Entry Submission";

        // Set the variables to null if not editing
        $id = NULL;
        $title = NULL;
        $img = NULL;
        $entry = NULL;
    }
?>
<!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" xml:lang="en" lang="en">

<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <link rel="stylesheet" href="/simple_blog/css/default.css" type="text/css" />
    <title> Simple Blog </title>
</head>

<body>
    <h1> Simple Blog Application </h1>

<?php

    if($page == 'delete'):
    {
        echo $confirm;
    }
    elseif($page == 'createuser'):
    {
        echo $create;
    }
    else:

?>

You are now able to navigate to http://localhost/simple_blog/admin/createuser and see your form (see Figure 11-1).

Figure 11.1. The form you use to create site administrators

11.2.2. Saving New Administrators in the Database

You submit your form to update.inc.php with a hidden input named action that sends the value, createuser. To store administrators created through your createUserForm() HTML form, you need to modify update.inc.php to catch form information with an action of createuser.

You need to prepare an SQL statement that places the username and password into the admin table. Do this after you ensure that the form was sent using the POST method, that the action is set to createuser, and that the username and password inputs were not submitted with empty values.

11.2.2.1. Dealing with Passwords

You need to take extra precautions now that you're dealing with passwords. Passwords are sensitive information, and you do not want to store a password as plain text in the database. Fortunately, both PHP and MySQL provide means for encrypting strings.

For the blog, you can use SHA1(), which is a basic encryption algorithm. Calling SHA1() on a string returns a 40-character string that is difficult to decode.

NOTE

For more information on encrypting passwords, look up the PHP manual entries on md5() and sha1().

11.2.2.2. Saving the Admin

To save the admin information, you need to include the database credentials and open a new connection to your database.

The SQL statement you use for this is a standard insert, except that you need to use MySQL's built-in support for creating SHA1 hashes. After you insert the new entry into the table, you send the user back to the default blog home page.

In update.inc.php, insert the following code in bold just before the last else block:

// If an admin is being created, save it here
else if($_SERVER['REQUEST_METHOD'] == 'POST'
    && $_POST['action'] == 'createuser'
    && !empty($_POST['username'])
    && !empty($_POST['password']))
{
    // Include database credentials and connect to the database
    include_once 'db.inc.php';
    $db = new PDO(DB_INFO, DB_USER, DB_PASS);
    $sql = "INSERT INTO admin (username, password)
            VALUES(?, SHA1(?))";
    $stmt = $db->prepare($sql);
    $stmt->execute(array($_POST['username'], $_POST['password']));
    header('Location: /simple_blog/'),
    exit;
}

else
{
    header('Location: ../'),
    exit;
}

?>

You can now save new administrators to your admin table. Navigate to http://localhost/simple_blog/admin/createuser in a browser and create a new user with the username of admin and the password of admin. Now click the Create button, navigate to http://localhost/phpmyadmin in a browser, select the simple_blog database and the admin table, then click the Browse tab. Your administrator is now saved in the table, and the password is saved as an encrypted hash (see Figure 11-2).

Figure 11.2. Your first administrator

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.97.75