PHP in web applications

Even though the main purpose of this chapter is to show you the basics of PHP, doing it in a reference-manual kind of a way is not interesting enough, and if we were to copy-paste what the official documentation says, you might as well go there and read it by yourself. Keeping in mind the main purpose of this book and your main goal is to write web applications with PHP, let us show you how to apply everything you are learning as soon as possible, before you get too bored.

In order to do that, we will now start on a journey towards building an online bookstore. At the very beginning, you might not see the usefulness of it, but that is just because we've still not shown all that PHP can do.

Getting information from the user

Let's start by building a home page. In this page, we are going to figure out if the user is looking for a book or just walking by. How do we find that out? The easiest way right now is to inspect the URL that the user used to access our application, and extract some information from there.

Save this content as your index.php:

<?php
$looking = isset($_GET['title']) || isset($_GET['author']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Bookstore</title>
</head>
<body>
    <p>You lookin'? <?php echo (int) $looking; ?></p>
    <p>The book you are looking for is</p>
    <ul>
        <li><b>Title</b>: <?php echo $_GET['title']; ?></li>
        <li><b>Author</b>: <?php echo $_GET['author']; ?></li>
    </ul>
</body>
</html>

Now access the link, http://localhost:8000/?author=HarperLee&title=To Kill a Mockingbird. You will see that the page prints some of the information that you passed on to the URL.

For each request, PHP stores all the parameters that come from the query string in an array called $_GET. Each key of the array is the name of the parameter, and its associated value is the value of the parameter. So $_GET contains two entries: $_GET['author'] contains Harper Lee and $_GET['title'] has the value To Kill a Mockingbird.

In the first highlighted line, we assign a Boolean value to the variable $looking. If either $_GET['title'] or $_GET['author'] exists, that variable will be true, otherwise false. Just after that, we close the PHP tag and then we print some HTML, but as you can see, we are actually mixing the HTML with some PHP code.

Another interesting line here is the second highlighted one. Before printing the content of $looking, we cast the value. Casting means forcing PHP to transform a type of value to another one. Casting a Boolean to an integer means that the resultant value will be 1 if the Boolean is true or 0 if the Boolean is false. As $looking is true since $_GET contains valid keys, the page shows a "1".

If we try to access the same page without sending any information, as in http://localhost:8000, the browser will say Are you looking for a book? 0. Depending on the settings of your PHP configuration, you will see two notice messages complaining that you are trying to access keys of the array that do not exist.

Note

Casting versus type juggling

We already know that when PHP needs a specific type of variable, it will try to transform it, which is called type juggling. But PHP is quite flexible, so sometimes, you have to be the one specifying the type that you need. When printing something with echo, PHP tries to transform everything it gets into strings. Since the string version of the Boolean false is an empty string, that would not be useful for our application. Casting the Boolean to an integer first assures that we will see a value, even if it is just a 0.

HTML forms

HTML forms are one of the most popular ways of collecting information from the user. They consist of a series of fields—called input in the HTML world—and a final submit button. In HTML, the form tag contains two attributes: action points where the form will be submitted, and method, which specifies the HTTP method that the form will use (GET or POST). Let's see how it works. Save the following content as login.html and go to http://localhost:8000/login.html.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Bookstore - Login</title>
</head>
<body>
    <p>Enter your details to login:</p>
    <form action="authenticate.php" method="post">
        <label>Username</label>
       <input type="text" name="username" />
        <label>Password</label>
       <input type="password" name="password" />
        <input type="submit" value="Login"/>
    </form>
</body>
</html>

The form defined in the preceding code contains two fields, one for the username and one for the password. You can see that they are identified by the attribute name. If you try to submit this form, the browser will show you a Page Not Found message, as it is trying to access http://localhost:8000/authenticate.php and the web server cannot find it. Let's create it then:

<?php
$submitted = !empty($_POST);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Bookstore</title>
</head>
<body>
    <p>Form submitted? <?php echo (int) $submitted; ?></p>
    <p>Your login info is</p>
    <ul>
        <li><b>username</b>: <?php echo $_POST['username']; ?></li>
        <li><b>password</b>: <?php echo $_POST['password']; ?></li>
    </ul>
</body>
</html>

As with $_GET, $_POST is an array that contains the parameters received by POST. In this preceding piece of code, we first ask if that array is not empty—note the ! operator. Afterwards, we just display the information received, just as in index.php. Notice that the keys of the $_POST array are the values for the argument name of each input field.

Persisting data with cookies

When we want the browser to remember some data like whether you are logged in or not on your web application, your basic info, and so on, we use cookies. Cookies are stored on the client side and are sent to the server when making a request as headers. As PHP is oriented towards web applications, it allows you to manage cookies in a very easy way.

There are few things you need to know about cookies and PHP. You can write cookies with the setcookie function that accepts several arguments:

  • A valid name for the cookie as a string.
  • The value of the cookie—only strings or values that can be casted to a string. This parameter is optional, and if not set, PHP will actually remove the cookie.
  • Expiration time as a timestamp. If not set, the cookie will be removed once the browser is closed.

Note

Timestamps

Computers use different ways for describing dates and times, and a very common one, especially on Unix systems, is the use of timestamps. They represent the number of seconds passed since January 1, 1970. For example, the timestamp that represents October 4, 2015 at 6:30 p.m. would be 1,443,954,637, which is the number of seconds since that date.

You can get the current timestamp with PHP using the time function.

There are other arguments related to security, but they are out of the scope of this section. Also note that you can only set cookies if there is no previous output from your application, that is, before HTML, echo calls, and any other similar functions that send some output.

To read the cookies that the client sends to us, we just need to access the array, $_COOKIE. It works as the other two arrays, so the keys of the array will be the name of the cookies and the value of the array will be their values.

A very common usage for cookies is authenticating the user. There are several different ways of doing so, depending on the level of security you need for your application. Let's try to implement one very simple—albeit insecure one (do not use it for live web applications). Leaving the HTML intact, update the PHP part of your authenticate.php file with the following content:

<?php
setcookie('username', $_POST['username']);
$submitted = !empty($_POST);
?>

Do the same with the body tag in your index.php:

<body>
    <p>You are <?php echo $_COOKIE['username']; ?></p>
    <p>Are you looking for a book? <?php echo (int) $lookingForBook; ?></p>
    <p>The book you are looking for is</p>
    <ul>
        <li><b>Title</b>: <?php echo $_GET['title']; ?></li>
        <li><b>Author</b>: <?php echo $_GET['author']; ?></li>
    </ul>
</body>

If you access http://localhost:8000/login.html again, try to log in, open a new tab (in the same browser), and go to the home page at http://localhost:8000, you will see how the browser still remembers your username.

Other superglobals

$_GET, $_POST, and $_COOKIE are special variables called superglobals. There are other superglobals too, like $_SERVER or $_ENV, which will give you extra information. The first one shows you information about headers, paths accessed, and other information related to the request. The second one contains the environment variables of the machine where your application is running. You can see the full list of these arrays and their elements at http://php.net/manual/es/language.variables.superglobals.php.

In general, using superglobals is useful, since it allows you to get information from the user, the browser, the request, and so on. This is of immeasurable value when writing web applications that need to interact with the user. But with great power comes great responsibility, and you should be very careful when using these arrays. Most of those values come from the users themselves, which could lead to security issues.

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

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