Difference between revisions of "User:Pegeraki/HB PHP"
Line 36: | Line 36: | ||
<div align="center"> | <div align="center"> | ||
− | + | {| class="wikitable" | |
− | + | !align="center" | Please Login: | |
− | + | |- | |
− | + | |Username: <input type="text" name="username"> | |
− | + | |- | |
− | + | |Password: <input type="password" name="password"> | |
− | + | |- | |
− | + | |align="center" | <input type="submit" name="submit" value="Login> | |
− | + | |} | |
− | |||
− | |||
− | |||
− | |||
− | |||
</div> | </div> | ||
Line 90: | Line 85: | ||
<p>Please login in:</p><BR> | <p>Please login in:</p><BR> | ||
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"><BR> | <form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"><BR> | ||
− | <table border="0" cellspacing="0" cellpadding="0"><BR> | + | <nowiki><table border="0" cellspacing="0" cellpadding="0"></nowiki><BR> |
− | <tr><BR> | + | <nowiki><tr></nowiki><BR> |
− | <td>Username:</td><BR> | + | <nowiki><td>Username:</td></nowiki><BR> |
− | <td><input type="text" name="username"></td><BR> | + | <nowiki><td><input type="text" name="username"></td></nowiki><BR> |
− | </tr><BR> | + | <nowiki></tr></nowiki><BR> |
− | <tr><BR> | + | <nowiki><tr></nowiki><BR> |
− | <td>Password:</td><BR> | + | <nowiki><td>Password:</td></nowiki><BR> |
− | <td><input type="password" name="password"></td><BR> | + | <nowiki><td><input type="password" name="password"></td></nowiki><BR> |
− | </tr><BR> | + | <nowiki></tr></nowiki><BR> |
− | <tr><BR> | + | <nowiki><tr></nowiki><BR> |
− | <td colspan="2"><input type="submit" name="submit" value="Login"></td><BR> | + | <nowiki><td colspan="2"><input type="submit" name="submit" value="Login"></td></nowiki><BR> |
− | </tr><BR> | + | <nowiki></tr></nowiki><BR> |
</table><BR> | </table><BR> | ||
</form><BR> | </form><BR> |
Revision as of 14:28, 27 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>
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
// Initialization of variables (database etc)
$db = mysql_connect('servername','user','login');
mysql_select_db('mydb');
// Take care of form submission
if (isset($_POST['submit'])) {
// Check form variables for errors
...
// Check if the user is in the db
$sql = 'SELECT count(*) as count
FROM users
WHERE username = "'.$_POST['username'].'"
AND password = "'.$_POST['password'].'"';
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if ($row['count'] == 1) {
// Correct login, send user to start page
header('Location: start.php');
}
}
// ----------------- START HTML OUTPUT ------------------
?>
<html>
<head>
<title>Login</title>
</head>
<body>
Please login in:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<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>
</form>
</body>
</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 tableusers
with the submittedusername
/password
combo (should be either zero or one). When we retrieve the query result, we refer the this number ascount
(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 pagestart.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 beforeheader()
is called (i.e. don't useecho
/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 filelogin.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.