User:Pegeraki/HB PHP

From WolfTech
Jump to navigation Jump to search

WolfTech Webteam Handbook

PHP Coding

What is by far the most important concept to keep in mind while writing PHP code, or for that matter any web-based code, is to separate the code from the content. By separating the code from the content, you place as much of the PHP, MySQL, and other queries at the top of the page as possible and then follow it with whatever HTML output you desire. A sample of what this might look like is considered below. In addition, comment your code so that you and others know what is going on inside the code. Adding a concise, informative blurb at the beginning of each code block can make a world of difference.

As the example shows, there is no PHP code in the lower half of the page. However, this is not very realistic for actual web pages. You will pretty much always have some variable to look up, table entry to query, etc which will prevent you from completely separating your code. The idea, though, is that we get as much of the PHP out of the way at the begining of the file, and only make minor calls later on. In the HTML part you should only need to output statements (echo/print) and control statements (if/for/while etc). Use of echo statements to output the main HTML should be avoided at all times. Also, NO SQL statements should appear in the lower part of the script. Also notice that the comments are kept to a minimum and tell us exactly what the next small chunk of code will do.

// Initialization of variables (database etc)

// Take care of form submission
if (isset($_POST['submit'])) {
// Check form variables for errors

// Do something with the form data

// Any other processing before we display the page

// ----------------- START HTML OUTPUT ------------------
<title>Cool page</title>

Cool content


Let's look at a more "real world" example - a login page for some application. We have a form with two input fields for username and password.

Please login:

Username: <input type="text" name="username">
Password: <input type="password" name="password">
<input type="submit" name="submit" value="Login">

First time the user loads the page, only the form is displayed. Once the form is submitted, the script checks if the user is registered in the database and if the password is correct. If this is correct, the user is redirected to a different page (presumably a start page in the application).

Here is the initial code (no error check for now, we'll add that later on):

<?php<BR> // Initialization of variables (database etc)<BR> $db = mysql_connect('servername','user','login');<BR> mysql_select_db('mydb');<BR> <BR> // Take care of form submission<BR> if (isset($_POST['submit'])) {<BR> // Check form variables for errors<BR> ...<BR> <BR> // Check if the user is in the db<BR> $sql = 'SELECT count(*) as count <BR> FROM users<BR> WHERE username = "'.$_POST['username'].'"<BR> AND password = "'.$_POST['password'].'"';<BR> $result = mysql_query($sql);<BR> $row = mysql_fetch_assoc($result);<BR> <BR> if ($row['count'] == 1) {<BR> // Correct login, send user to start page<BR> header('Location: start.php');<BR> }<BR> }<BR> <BR> // ----------------- START HTML OUTPUT ------------------<BR> ?><BR> <html><BR> <head><BR> <title>Login</title><BR> </head><BR> <body><BR> <p>Please login in:</p><BR> <form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"><BR> <table border="0" cellspacing="0" cellpadding="0"><BR> <tr><BR> <td>Username:</td><BR> <td><input type="text" name="username"></td><BR> </tr><BR> <tr><BR> <td>Password:</td><BR> <td><input type="password" name="password"></td><BR> </tr><BR> <tr><BR> <td colspan="2"><input type="submit" name="submit" value="Login"></td><BR> </tr><BR> </table><BR> </form><BR> </body><BR> </html>

Most stuff here should look familiar, but let's look at a few details.

  • The database query SELECT count(*) as count counts the number of records in the table users with the submitted username/password combo (should be either zero or one). When we retrieve the query result, we refer the this number as count (called an alias). So if $row['count'] is equal to 1, then we have a legit user and will make a redirect to our start page start.php.
  • The header() function allows us to send a raw HTTP header to the user's browser telling it to go to a different URL. It's important to note that no output can be sent to the browser before header() is called (i.e. don't use echo/print).
  • The form attribute action contains a small block of PHP code:

    <?php echo $_SERVER['PHP_SELF']; ?>

    This will translate into the name of the login script. So if we name the file login.php the form tag will translate to:

    <form method="POST" action="login.php">

    That is, the form will keep submitting to itself, even if we later on change the file name. This can be quite handy.

While this is a working script, it would be nice to have some error checking (right now, the user wouldn't know if a form error occured or if the user wasn't in the database). Also, in case of errors, we want to tell the user what's going on. To keep this simple, let's just check that the fields are not empty. If either one of them are, display an error message to the user. This would look something like:

Please login:

You need to fill out both fields.

Username: <input type="text" name="username">
Password: <input type="password" name="password">
<input type="submit" name="submit" value="Login">

...and here's the code:

<?php highlight_file('codeStructure_ex3.txt'); ?>

Some notes on the code:

  • Before the form check, we use trim() to get rid of any blanks before or after the inputs. For example, if someone just enters a blank space in one of the text boxes, the string will be empty after the trim and we won't have to bug the database server with a user lookup.
  • The actual form check doesn't check which field contains an error - it might be both. Since we only have two text-boxes this is not a big deal. However, for larger forms it's definitely a good idea to tell the user which fields contain errors. In such a form, we would also redisplay the form values so the user wouldn't have to type it all in again. In our login form the fields will be blank if there's an error.
  • There's a new variable $errorMsg that's initialized to an empty string (i.e. no errors yet). If a field is blank or if the user is not found in the database, we put our message in $errorMsg.
  • As for the HTML part of the code, we have two PHP segments. One is same as before, that is for automatically getting the file name in the form tag. The new segment is for displaying the error message. If the $errorMsg is an empty string, we won't do anything. If it's not empty, we display it (in red!).

The last code example gets users from a table in the database and displays each one in an HTML table. This just demonstrates how you can handle queries in your code without having to put it in the HTML section. We're using PHP in the HTML section only to loop over the query result set and display it.

<?php highlight_file('codeStructure_ex4.txt'); ?>

The examples above are very simple, but regardless how complex your scripts get, you should always try and keep your code in two parts. If you use CSS and javascript that you use in multiple pages, make them separate files, that is *.css and *.js files and include them in the HTML <head> tag.

Also, don't forget to put comments in your code! You don't need to put comments everywhere, before each minor code block is ok (unless you have a really tricky piece that needs more explanation).

Separating code and presentation is nothing new. However, in a language like PHP it's so easy to just start coding and not pay attention to the code structure. If you're code is divided like described here it will be much easier for everyone to work with it.