Difference between revisions of "User:Pegeraki/HB PHP"

From WolfTech
Jump to navigation Jump to search
 
(2 intermediate revisions by the same user not shown)
Line 33: Line 33:
 
</code></p>
 
</code></p>
  
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.
+
In addition, <strong>do not forget to put comments in your code!</strong> 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).
 
 
<div align="center">
 
<p>Please login:</p>
 
<table border="0" cellspacing="0" cellpadding="0">
 
<tr>
 
<td>Username:</td>
 
<td><nowiki><input type="text" name="username"></nowiki></td>
 
</tr>
 
<tr>
 
<td>Password:</td>
 
<td><input type="password" name="password"></td>
 
</tr>
 
<tr>
 
<td colspan="2"><input type="submit" name="submit" value="Login"></td>
 
</tr>
 
</table>
 
</div>
 
 
 
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):
 
 
 
<p style="margin-left: 10px; background-color: #F0F0F0; border: 1px solid black; padding: 5px; width: 76%"><code>
 
<nowiki><?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></nowiki></code></p>
 
 
 
Most stuff here should look familiar, but let's look at a few details.
 
 
 
<ul>
 
<li>
 
The database query <code>SELECT count(*) as count</code> counts the number of records in the table <code>users</code> with the submitted <code>username</code>/<code>password</code> combo (should be either zero or one). When we retrieve the query result, we refer the this number as <code>count</code> (called an <i>alias</i>). So if <code>$row['count']</code> is equal to 1, then we have a legit user and will make a redirect to our start page <code>start.php</code>.
 
</li>
 
<li>
 
The <code>header()</code> 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 <code>header()</code> is called (i.e. don't use <code>echo</code>/<code>print</code>).
 
</li>
 
<li>
 
The form attribute <code>action</code> contains a small block of PHP code:<br><br>
 
<code>&lt;?php echo $_SERVER['PHP_SELF']; ?&gt;</code><br><br>
 
This will translate into the name of the login script. So if we name the file <code>login.php</code> the form tag will translate to:<br><br>
 
<code>&lt;form method="POST" action="login.php"&gt;</code><br><br>
 
That is, the form will keep submitting to itself, even if we later on change the file name. This can be quite handy.
 
</li>
 
</ul>
 
 
 
 
 
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:
 
 
 
<div align="center">
 
<p>Please login:</p>
 
<p style="color: red">You need to fill out both fields.</p>
 
<table border="0" cellspacing="0" cellpadding="0">
 
<tr>
 
<td>Username:</td>
 
<td><input type="text" name="username"></td>
 
</tr>
 
<tr>
 
<td>Password:</td>
 
<td><input type="password" name="password"></td>
 
</tr>
 
<tr>
 
<td colspan="2"><input type="submit" name="submit" value="Login"></td>
 
</tr>
 
</table>
 
</div>
 
 
 
...and here's the code:
 
 
 
<div class="codeBox">
 
<?php highlight_file('codeStructure_ex3.txt'); ?>
 
</div>
 
 
 
Some notes on the code:
 
<ul>
 
<li>
 
Before the form check, we use <code>trim()</code> 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.
 
</li>
 
<li>
 
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.
 
</li>
 
<li>
 
There's a new variable <code>$errorMsg</code> 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 <code>$errorMsg</code>.
 
</li>
 
<li>
 
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 <code>$errorMsg</code> is an empty string, we won't do anything. If it's not empty, we display it (in red!).
 
</li>
 
</ul>
 
 
 
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.
 
 
 
<div class="codeBox">
 
<?php highlight_file('codeStructure_ex4.txt'); ?>
 
</div>
 
 
 
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, <strong>don't forget to put comments in your code!</strong> 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.
 
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.

Latest revision as of 14:19, 31 March 2006

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.

<?php
// 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 ------------------
?>
<html>
<head>
<title>Cool page</title>
</head>
<body>

Cool content


</body>
</html>

In addition, do not 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.