Handling User Input with PHP

PrevMain 
php-tutorial-part2

We are going to handle user input step-by-step here, starting with a simple username/password form and working our way to handling the input on the back end.

Creating The HTML Form

If you’re familiar with HTML, you’ll know that it has the ability to create forms (if you’re not familiar with HTML, Google a few HTML tutorials before you continue: it’ll save you more than a few headaches in the long run!). For example, create a PHP script called "login.php" and copy and paste these lines, the form we’re going to use for our username and password concoction:

<html>
<title> Super-Secret Password Page </title>
  <body>
    <form method="post" action="login.php">
      <br />
      Username:  <input type="text" size="12" name="username" />
      <br />
      Password: <input type="text" size="12" name="password" />
      <br />
      <input type="submit" value="Log in" name="submit" />
    </form>
  </body>
</html>

It’s a pretty simple form, if a little bare (we’re not going for points for design here, this is a programming tutorial, after all, and super-secret code pages are sparse and intimidating). It should look like this:

login window

Many of you will immediately notice two things: there’s no PHP code in here, and that the first <form> tag has the action pointing to "login.php" instead of a more traditional HTML call like "mailto" or ones you may be familiar with. What that line means is that the form will take the results the user submitted and send them to "login.php", which in our case is the same file (you can have it point to whatever PHP file you want, so long as that file has a function to handle the variables the HTML sends it.) Some people prefer to have all their HTML in files that end in .html and all their PHP in files that end in .php; it’s up to you how you want to do it. For this tutorial and how simple it is it’s cumbersome, however, to have separate HTML and PHP files, so we’re going to have the form send to the same page and put everything in login.php.

Handling the user input

Open up that page again, and insert the following code before the HTML code:

$username = $_POST["username"];
$password = $_POST["password"];

if (!isset($_POST['submit'])) {
  // your code here
}

There are quite a few new concepts right here that we’ll have to explain. First off, you’ll notice that all of these are variables; when you click submit, the user input gets passed to the _POST variable with the name you gave it in the form (in our case, username and password). $_POST is in and of itself an array, and because using the $_POST global variable is long, we make easier variables to remember, in this case $username and $password, to put username and password in.

For those of you coming from other programming languages, it’s important to note here that PHP is dynamically typed; you don’t have to declare the type of variable before you use it. There’s no need to specify whether something is an integer, a float, or a string; simply initialize the variable with whatever value you want and PHP will figure out what type it should be.

The if statement here uses a special function of PHP here called isset(), and isset is a function that, as befits its name, checks whether or not a variable has been set. In this case, we’re checking if the user has pressed the submit button, and if they haven’t, we can assume they haven’t seen the form and so we show them the form.

There is another method of passing variables , which you’ve probably seen before: the GET method, which passes variables in the URL. Here’s an example of a URL that’s using a get method:

http://www.example.com/index.php?id=testpage

In this case, the id "testpage" has been passed via GET, and variables passed in GET appear right in the URL. We’re always going to use POST, for the simple reason that it’s slightly more secure than GET. There are reasons for using GET, and you’ll hear some people argue for it, but none of those scenarios will show up in any of these tutorial sets. For now, just always use POST; the moment you can think of a reason to use GET, you’ll know enough about PHP and server-side information handling that you’ll be informed enough to make a good decision about it on your own.

So now we’ve passed variables successfully, but the code still isn’t really doing anything. Doing things with the variables, however, requires us to do a little more than just push them around. Let’s take a look at what we can do with them.

Comparing Strings

Let’s say that only John Smith is allowed to access the super-secret page with his username 'jsmith' and his password 'john123'. We want to have the page allow him in if his user input matches the username and password we have on file, so let’s go ahead and do that. Here’s the code snippet you’re going to add at the end of the file:

$gooduser = strcmp($username, 'jsmith');
$goodpass = strcmp($password, 'john123');

if ($goodpass == 0  && $gooduser == 0) {
  echo "Welcome, John Smith. Here are the Super-Secret passcodes.";
} elseif (isset($_POST['submit']) && ($goodpass != 0 || $gooduser != 0)) {
  echo "incorrect username or password.";
}
?>

There’s a few new things here as well, and we’ll take the time to go over them. The first thing you’ll notice are the else and elseif statements; these work just as they do in other programming languages. If the first if statement we put in all the way at the top is false, then the next elseif runs; if that is also false, we run the last else. In this case, we’re comparing strings, and we’re using a function to do so: the strcmp() function. It takes two strings, compares them, and if they’re identical it returns true. strcmp() is case-sensitive; the login will fail if the user puts in "JSMITH" or "JOHN123". If you want to compare two case-insensitive strings, you can use the function strcasecmp(). If we used that, "JSMITH" and "JOHN123" would work just fine.

Save that, and let’s try the code. To make it easier to compare what you should have with what you have, here’s what the entire login.php should look like:

<?php
$username = $_POST["username"];
$password = $_POST["password"];

if (!isset($_POST['submit'])) {
?>
<html>
<title> Super-Secret Password Page </title>
  <body>
    <form method="post" action="login.php">
    <br />
    Username:  <input type="text" size="12" name="username" />
    <br />
    Password: <input type="text" size="12" name="password" />
    <br />
    <input type="submit" value="Log in" name="submit" />
    </form>
  </body>
</html>
<?php
}

$gooduser = strcmp($username, 'jsmith');
$goodpass = strcmp($password, 'john123');

if ($goodpass == 0 && $gooduser == 0) {
  echo "Welcome, John Smith. Here are the Super-Secret passcodes.";
} elseif (isset($_POST['submit']) && ($goodpass != 0 || $gooduser != 0)) {
  echo "incorrect username or password.";
}
?>

You should get a page that looks like this:

login window

If you put in the right username and password, you get this:

welcome window

And if you put in the wrong username / password, you’ll see this:

incorrect login window

It’s possible you’ll get an error; if so, go back and check the code. It’s very easy to make a mistake while typing the code blocks in, and a stray curly brace, bracket, or typo can cause untold amounts of weird bugs and errors in your code. Sometimes, it doesn’t even cause errors, and instead you simply get weird mistakes that end up with your program running, but not running the way you want it to and giving you strange results.

What’s Next

Congratulations! You’ve successfully had a user input data into forms and taken and processed that data in order to show different results based on the data. You probably noticed, however, that this login script has more than a few limitations; one of which is that our login script only allows for one user. If anyone else had to access our super-secret data other than John Smith, it would get pretty hairy pretty quickly to add all those usernames and passwords into the file.

It’s for this reason that databases like MySQL were invented, and the pairing of PHP and MySQL is a powerful combination that powers many big websites and will power our super-secret login website in the next part of this tutorial!

PrevMain