Logging In with Cookies PHP Help

You know what cookies are, and you know the flow of the sign-in form. Now, it’s time to write some code. Create signin.php and start with the basic outline:

Logging In with Cookies

This script is far from complete and has several problems, but it’s still a lot of code. Let’s take it piece by piece.

Determining Whether the User Is Already Signed In

Even if a user comes to your sign-in page explicitly, you shouldn’t make him sign in if he’s already in. So the first thing to do (other than a few require_once lines) is establish whether the “user jd” cookie is set. If it’s not, the user is not logged in, and everything flows from there.

Determining Whether the User Is Already Signed In

Here’s your first clue that cookies aren’t much different than what you’ve already been using: you can use isset to see if it’s already created and then you just pass in the cookie name. Piece of cake.

Is the User Trying to Sign In?

If the “user id” cookie isn’t set, the user is not logged in. The next thing to check, then, is whether he’s trying to log in. This would mean that you have some request information. In fact, the user might have filled out the HTML form already (later in this script) and submitted that form back to this script.

However, that’s not the same as trying to access this script without any information. In that case, the user should just get the regular HTML sign-in form. As a result you can see whether there’s a submission by checking if there’s anything in the $_REQUEST superglobal for “username,” a field from the sign in form:

Is the User Trying to Sign In.

If there’s request data, you can get the user name and password that have been submitted, and (in a moment) look up the user and deal with any problems.

Before you do that, though, there’s a nice change you can make. So far, you’ve been using $_REQUEST for everything. It takes in GET requests-which are requests where information is passed through the URL-and POST requests, like the ones that most of your forms have issued. But, you already know that the only way information should get to this stage is by a submission from your own form, which will use a POST request.

It would probably be better to replace $_ REQUEST with a more specific superglobal: $_POST,which only has request data from a POST request.

It’s a good idea to begin moving toward the more specific $_POST when possible. POST data prohibits parameters on the request URL, and it’s generally a bit more secure.

Make that small change to your script:

Is the User Trying to Sign In.

Post It or Get It?

Ahh, yes, another Quibble over which programmers can argue, demonize, and distort. No matter what you hear, there’s just no functional difference between $_REQUEST, $_GET, and $_POST in terms of getting request information. $_REQUEST will always have what’s in both $_GET and $_POST, but if you know you’ve got a POST request, you don’t gain or lose anything by using $_REQUEST over $_POST.

In fact, not only does $_REQUEST have the combined values from $_GET and $_POST, it has the contents of $_COOKIE in it too (at least by default). Technically, you could do this in signin.php

// If the user is logged in, the
// user_id cookie will be set
if (lisset($_REOUEST[‘user_id’))

In other words, you could use $_REQUEST and totally ditch $_GET, $_REQUEST, and $_COOKIE. But, think back to all the programming principles you’ve been learning: make your code clear and readable; be specific over being just generic; and think about what those who have to work with your code after you will see. For all of those reasons, although $_REQUEST isn’t bad, it’s often helpful to use $_GET and $_POST and $_COOKIE when that’s what you’re dealing with.

In the case of signin.php you know you’re getting a POST request. Given that, use $_ POST when you can. If you know you’re getting a GET request, use $_GET. And if you’re looking for a cookie, use $COOKIE. Your code will be clearer and more specific, and most of all, you’ll know exactly what it’s intended to do.

Displaying the Page

Whether the user got to this page by submitting incorrect credentials or by submitting no credentials at all, she should see a form. You’re now ready to display some HTML.

Displaying the Page

Don’t miss that opening comment block; it’s an important one. This code, including the HTML, is all still part of the opening if block:

// If the user is logged in, the user_id cookie will be set
if (!isset($_COOKIE[‘user_id’]» {

In other words, all of this HTML is shown if, and only if, the user is not logged in.

There’s another small improvement you can make here, in the same vein as using $_POST instead of $_REQUESTT.ake a look at this line:

<Form id=”signin_form” action=”signin.php” method=”POST”>

This line instructs the form to submit to the same script that’s generating the form. There’s nothing wrong with it, but what if you were to rename signin.php It might be a remote possibility, but all the same, it’s not unrealistic. (It wasn’t that long ago that you moved away from calling a script admin.php and instead went with the more functionally named delete_user.php and show_users.php.)

Remember that PHP loves this script-submitting-to-script paradigm. In fact. just to make it a bit easier, there’s a property in $_ SERVER that furnishes the current script name. No, it’s not there just for self-referential scripts, but it sure does help. Update signin.php to take advantage of $_SERVER[‘ PHP_SELF’]:

<form id~”signin_form”
action=”<?php echo $_SERVER[‘PHP_SElF’]j ?>”

With this addition, the form submits, literally, to itself. A small change, but a good one, and one you’ll find yourself coming back to over and over again.

Redirecting as Needed

The only thing left, at least in this pseudocode version, is to redirect the user if she’s- logged in:

} else (
// Now handle the case where they’re logged in
// redirect to another page, most likely show_user.php

You have the basic flow, but there’s loads of stuff missing. Time to dig in and start piecing this code into a usable form. (For more advice on how to get started, see the following box.)

Pseudocode with Comments and Real Code

It might seem strange to think of signin.php as it currently exists as pseudocode, but that’s just what it is. It’s certainly not a complete working script; there are numerous holes through which you could drive a truck. Fortunately, those holes are generally indicated with a helpful, clear comment. Although those comments don’t do anything programmatically, they do remind you of what need to do and where you need to do it. Truth be told, pseudocode is often best done in just this way. You’re not wasting time writing non-existent function names like check_the_user_credentialsO. But you’re accomplishing the same goal with comments like:

// Look up the user
// If user not found, issue an error
Those comments are just as useful, and they can stay put as you write code under each comment that fills out the script’s functionality.

Before you begin, though, you can already get a good idea of this flow. Right now, a non-logged-in user will get the HTML output. without all the PHP that runs when there’s a user name coming in through a POST request. As a result. Figure 13-3 is the default view, so to speak.

When you try to submit the form-with a good or bad user name-you get the same form over again. Not so great. but it’s a place to start, and you can begin to tackle each individual piece of functionality.



Logging In the User

The next bit of code is nothing more than a copy-paste-and-modify job from authorize.php Here’s where that script left off:

Logging In the User

Pretty good, although it all depends on HTTP authentication. Now, you can drop that into sign.php change the successful block to set some cookies, and redirect somewhere useful:

Logging In the User

Open up signin.php and you should see the login form (refer back to Figure 13-3 to ensure that you’re on the right page with the right HTML). Use some valid credentials, and you should successfully log in, have a cookie set, and be passed over to show_users.php (see Figure 13-4).



Did you notice anything odd in that last bit of redirection? Here’s the line where the redirect is sent to the browser:

Logging In the User

If no bells are ringing, check out Create_users.php (page 214). That script creates a user and redirects her to create_users.php. Here’s the relevant line:

header(“Location: show_user.php?user_id=” . mysql_insert_id()j

He’re, additional information is sent: the user _id of the user to display, sent as a GET parameter within the request URL. However, in siqnin 0110, there’s no user _id parameter. Figure 13-4 confirms that things work.

All the same, ‘show_user.php expects that information:

// Get the user 10 of the user to show
$user_id = $_REOUEST[‘user_id’];

So, how does this work in signin.php? The answer lies in how $_ REQUEST works and what information it contains. For starters, read the box on page 429 if you haven’t already, You’re setting a cookie in signin.php, and that cookie is accessible through the $_COOKIE superglobal. But, $_ REQUEST also contains what’s in $_COOKIE-along with what’s in $_POST and $_GET, As a result, this

$user_id = $_REOUEST[‘user_id’];

is actually just as good as the following for getting the value in a cookie:

$user_id = $_COOKIE[‘user _ id’] ;

Posted on January 14, 2016 in Cookies, Sign- Ins, and Ditching Crummy Pop-Ups

Share the Story

Back to Top
Share This