OUR MUST POPULAR POST

Thursday, April 25, 2013


Thursday, April 11, 2013

PHP Tutorial: Saving Sessions in a File

Having created a session and saved session data for use across iterations of pages within a session, we can see that there would be one more very useful capability.  What if we could save session information from one session to another, returning to information that was saved perhaps a few days ago?  PHP provides this capability by enabling you to save session information in a file.
A particularly useful example of the application of this ability, is to capture and refer to username and password information.  You could, for example, create a login page where a visitor can enter their user Id (their email address, perhaps) and their password,  You would then retrieve session information from an earlier session, based on their user Id, and present them with customized views of the rest of your site, based on other stored session variables that you retrieve from the file.  Such a project would, of course, require a little more code that is shown in this tutorial, but the methods used to save and retrieve the session data are right here!
Another great example of the use of this feature is in conjunction with a shopping cart.  Suppose you have a shopping cart that builds an order as the user makes their selections and stores that information somewhere based on a unique identifier such as a combination of their user Id and the session number.  Now suppose their connection is interrupted and their session is lost.  If you had saved their original session information in a file, then when they reconnected and logged back into your site, you would have all the information you would need to retrieve their partially completed order.  That would make for a happy shopper!
And so to the technique, which is simple enough: we're going to use the fopen function to open our file, the session_encode function to encode our session information into a string, the fputs function to write it into our file and the fclose function to close the file. Here's an example:
<?php
session_register("username");
session_register("password");
session_register("ordernumber");
$username = "Goody";
$password = "mypass";
$ordernumber = "1234";
$sessionfile = fopen("sessionfile.txt", "w");
fputs($sessionfile, session_encode( ) );
fclose($sessionfile);
?>
As you can see, we are creating three session variables to hold the information we will need and, in this example, are simply populating those variables from text strings. you will remember from the file system tutorial in this series about file use of the file functions shown here.  You can see here that in the fputs instruction we are using the session_encode function to take all our session information (which includes all our session variables, but does not include the session number) and encode it into a string which becomes the information we write (fputs) to our file.
Now that we have our information safely tucked away, we need a method to retrieve it again when we need it.  For this, we'll use the fgets function to get the record and the session_decode to retrieve the session information from the record returned.  Here we go:
<?php
session_start( );
?>
<html><head> ....... etc.
<?php
$sessionfile = fopen("sessionfile.txt", "r");
session_decode(fputs($sessionfile,  4096) );
fclose($sessionfile);
?>
There are a couple of things to notice here.  First, you'll see that we started a new session (with the session_start coming before anything else, as required - remember that from here?) because we need to have an active session to be able to create the session_variables, which is what the session_decode is going to do.
Next you'll notice that the session_encode and session_decode instructions are written the other way round from each other, with respect to their associated fputs and fgets functions.  Think of it like this: when writing, we want to write the result of the session_encode so the fputs contains the session_encode; when reading, we want to decode the result of the fgets function, so the session_decode contains the fgets.  (Technically, it may be inaccurate to speak of one "containing" the other, but it certainly helps to think of it that way!)

Another thing to watch out for is the scope of our variables (remember scope form the functions tutorial?)  In the first example above, we have specific statements to define the session variable, so their scope may be more obvious, but in the second, the variable will be defined by the session_decode function and so the scope might not immediately occur to you.  In either case, if the definition of the variable occurs within a function (that is, you have written these instructions inside some function) the scope of the session_variables will be local to that function.  If that's not what you want, you would have to add the "global" parameter.  In the second example above, this would mean adding a global definition for the variables prior to invoking the session_decode function, like this:

$sessionfile = fopen("sessionfile.txt", "r");
global $username, $password, $ordernumber;
session_decode(fputs($sessionfile,  4096) );
fclose($sessionfile);

Finally, you might want to think a little about the file name you use.  In these examples we used a file called "sessionfile.txt".  It might be more useful to you to name your file something else, such as the user Id, or a combination such as the user Id and an application identifier (for example, "vincebarnesorders.txt") so that you will know which file to get your session information from when the user comes back into your page.

PHP Tutorial: Sessions

There is a relationship between Sessions and Cookies -- they serve somewhat the same purpose, and are, to a certain extent, usable interchangeably.  Sessions, which were integrated into PHP in version 4 of the language, are a means to store and track data for a user while they travel through a series of pages, or page iterations, on your site.
The most significant differences between the two are that cookies are stored on the client, while the session data is stored on the server.  As a result, sessions are more secure than cookies (no information is being sent back and forth between the client and the server) and sessions work even when the user has disabled cookies in their browser.  Cookies, on the other hand, can be used to track information even from one session to another by setting it's time( ) parameter (see http://www.htmlgoodies.com/php/p14cookies.html)
How Sessions Work
Sessions in PHP are started by using the session_start( ) function.  Like the setcookie( ) function, the session_start( ) function must come before any HTML, including blank lines, on the page.  It will look like this:
<?php
session_start( );
?>
<html>
<head> ....... etc
The session_start( ) function generates a random Session Id and stores it in a cookie on the user's computer (this is the only session information that is actually stored on the client side.)  The default name for the cookie is PHPSESSID, although this can be changed in the PHP configuration files on the server (most hosting companies will leave it alone, however.)  To reference the session Id in you PHP code, you would therefore reference the variable $PHPSESSID (it's a cookie name; remember that from Cookies?)
Your sharp mind may be wondering what happens when you come to the second pass through your page and reach the session_start( ) function again.  PHP knows that there is already a session on progress and so ignores subsequent instances of the session_start( )   -- phew!!
Using Session Data
Having established a session, you can now create, store and retrieve information pertaining to that session.  You might want, for example, to keep track of items in your visitor's shopping cart.  Information for sessions is stored in a special directory on the server; the path of that directory is specified in the server's PHP configuration files.
Information to be stored for a session is kept in session variables.  Session variables are created by registering them for the session, using the session_register( ) function.  To use that information (on any page iteration in the session) you simply reference the variable just like you would any other variable.  Here's an example:
<?php
session_start( );
?>
<html>
<head>
<title>Using a session variable</title>
</head>
<body>
<?php
print "Welcome to session number: ";
print $PHPSESSID;
?>
<br />
<?php
session_register("username");
$username = "Goody";
print "Your name is: ";
print $username;
?>
</body>
</html>
In this example we have created a session and displayed the session number.  We then registered a session variable called username (notice the quotes around the variable's name in the call to the session_register( ) function.)
Next we assigned a value to that variable with the " = " assignment operator (remember operators from http://www.htmlgoodies.com/php/p05expressions.html?) and then displayed the value of that session variable.
We now have all the basic tools to establish a session, and to create and use variables that last through the entire duration of the session.

PHP Tutorial: Cookies

You are probably familiar with cookies from your time with our HTML tutorials (or from your experience with HTML), but just to recap, cookies are pieces of data that are stored as simple little text files in the site visitor's computer, and allow the site server to keep track of what a visitor is doing during their visit (or even across multiple visits.)  Some people think of cookies as bad or evil things, because they are sometimes used by advertisers to track an individual's browsing habits.   Any decent anti-spyware program can prevent that kind of thing, however, and cookies are a useful and necessary mechanism for such things as personalized sites (where you first log in, and are then presented your personalized version of the site), shopping carts and the like.
Creating a Cookie
PHP provides full support for cookies.  Creating a cookie is a simple matter, but there is an important timing consideration to remember.  If you are going to send a cookie down to the user's system, you must send it down before you send anything else; before any part of the page itself is sent, even before a blank line!  A cookie is sent by using the setcookie( ) function.  Here's an example:
<?php
setcookie ("cookiename", "This text will be in the cookie");
?>
<html>
<head> ....... etc.
Here you can see a cookie being sent with the name "cookiename" and containing the value "This text will be in the cookie".  Also, you can see that it is sent before ANY of the HTML code on the page itself is sent.  You can send more than one cookie, if you need to, by using more setcookie( ) function calls, but remember that the protocol has a limit of twenty cookies from one site to a single user.
Reading a cookie
When a user visits a PHP page that could read a cookie that is present in the user's computer at the time they call for the page, PHP automatically reads the cookie into a variable named the same as the cookie, but prefixed with a $ sign.  (Note that for this reason you should follow PHP variable naming conventions when creating your cookies - no spaces, for example!)  So, to read our cookie, we would simply reference it's variable name like this:
<?php
print "our cookie says $cookiename";
?>
This would show up on the page as:
our cookie says This text will be in the cookie
Simple enough!
Deleting a cookie
When cookies are created, they are set by default to be deleted when the user closes their browser.  You can override that default by setting a time for the cookie's expiration like this:
<?php
setcookie ("cookiename", "This text will be in the cookie", time( ) + 3600);
?>
<html>
<head> ....... etc
The addition of the time( ) parameter followed by a plus sign and a number of seconds sets the amount of time from now at which point the cookie is to expire.  In our example, the cookie will expire one hour from now.

There may be occasions when you need to delete a cookie before the user closes their browser, and before its expiration time arrives.  To do so, you would use the setcookie( ) function with the appropriate name for the cookie and with a time( ) parameter with a negative number, like this:
<?php
setcookie ("cookiename", "", time( ) - 1);
?>
Notice that we have left the contents parameter in its proper place, but with nothing in it.  Remember also that the setcookie( ) function call has to come before anything else on the web page.
Being able to manipulate cookies, we will now be able to manipulate information within a user's session, remembering it from page iteration to iteration, and from page to page.

PHP Tutorial: Error Handling

PHP Tutorial: Error Handling

It is the mark of a good programmer that they do not stop once they have found a way to make something work.  Instead, the conscientious programmer sets about finding every way that their solution might not work, and then writes some code to cover those situations.  Quality program code handles all foreseeable error situations, gracefully informing the user of the error that has occurred, and not just crashing, going away and leaving the user's mouth hanging open having just said "wha'....???"
This type of code is known as Error Handling, and we're going to apply some to the file upload solution we just created.  This was our "getfile.php" page:
<html>
<head>
<title>Process Uploaded File</title>
</head>
<body>
<?php
move_uploaded_file ($_FILES['uploadFile'] ['tmp_name'],
       "../uploads/{$_FILES['uploadFile'] ['name']}")
?>
</body>
</html>
 
Now we have to think of the kinds of error situations that might occur.  The first, and perhaps the most obvious, is that something goes wrong in the middle of the file transfer, and only a part of the file makes it through.  It is also possible that for some reason (perhaps to do with the user's file selection, or permissions or any other such reason) no file was uploaded at all.
There are also some possible errors that could arise because of capabilities in PHP itself.  PHP can be configured on the server to only allow file transfers of files up to a certain size.  When this size is exceeded, an error occurs.  We can also set a file size limit ourselves by adding a MAX_FILE_SIZE limit to our HTML form.  To do this, we would add a line like this one inside our <form>:
<input type="hidden" name="MAX_FILE_SIZE" value="25000" />
I'm showing a maximum size of 25,000 bytes here, but you can use any size you wish.
Now to handle those errors!  PHP is not going to leave us high and dry.  Instead, it includes some very helpful features.
First, we need to know if our file upload was successful or if any error occurred.  Happily, we can test the result of the move_uploaded_file function directly.  If it was successful, it will return "true", if any error occurred, it will return "false", which enable us to test it with an "if" statement like this:
if ( move_uploaded_file ($_FILES['uploadFile'] ['tmp_name'],
       "../uploads/{$_FILES['uploadFile'] ['name']}")  )
      {  print '<p> The file has been successfully uploaded </p>';
       }
else
      {   // error handling code goes here
       }
In this example, I've left out the actual error handling code for the moment so that you can clearly see how the "if" tests the true/false return from the move_uploaded_file function.
Now we need to find out what kind of error occurred and do something about it.  You will remember from the last part of this series that we discussed the $_FILES array and is associative indexes.  There is anothe such index called 'error' that returns a value to indicate what kind of error has occurred. We can conveniently test this value by using a "switch....  case" construct.
A "switch....  case" construct is like coding a series of "if.... else" statements, except that it is much tidier and easier to read.  Basically the "switch" part specifies a variable to be tested for a series of values, and the "case" parts say what to do in "case the value is this".  This is what it looks like when it is applied to our example:
switch ($_FILES['uploadFile'] ['error'])
 {  case 1:
           print '<p> The file is bigger than this PHP installation allows</p>';
           break;
    case 2:
           print '<p> The file is bigger than this form allows</p>';
           break;
    case 3:
           print '<p> Only part of the file was uploaded</p>';
           break;
    case 4:
           print '<p> No file was uploaded</p>';
           break;
 }
We now have code to handle the error situation we discussed earlier!  Putting it all together, we get the following code (showing first the form, then the PHP page that handles the form):
<html>
<head>
<title>File Upload Form</title>
</head>
<body>
This form allows you to upload a file to the server.<br>
<form action="getfile.php" method="post"><br>
Type (or select) Filename: <input type="file" name="uploadFile">
<input type="hidden" name="MAX_FILE_SIZE" value="25000" />
<input type="submit" value="Upload File">
</form>
</body>
</html>
and now the PHP page to handle the form:
<html>
<head>
<title>Process Uploaded File</title>
</head>
<body>
<?php
if ( move_uploaded_file ($_FILES['uploadFile'] ['tmp_name'],
       "../uploads/{$_FILES['uploadFile'] ['name']}")  )
      {  print '<p> The file has been successfully uploaded </p>';
       }
else
      {
        switch ($_FILES['uploadFile'] ['error'])
         {  case 1:
                   print '<p> The file is bigger than this PHP installation allows</p>';
                   break;
            case 2:
                   print '<p> The file is bigger than this form allows</p>';
                   break;
            case 3:
                   print '<p> Only part of the file was uploaded</p>';
                   break;
            case 4:
                   print '<p> No file was uploaded</p>';
                   break;
         }
       }
?>
</body>
</html>
 
We now have a much more elegant file upload process!

PHP Tutorial: Uploading Files

In previous parts of this series, we've discussed the basics of forms (see parts three and four) and we've introduced the basics of file manipulation.  Now we're going to put this together, throw a little spice into the mix, and create a form that will allow for a file to be uploaded.
The Form
Let's start with the form:
<html>
<head>
<title>File Upload Form</title>
</head>
<body>
This form allows you to upload a file to the server.<br>
<form action="getfile.php" method="post"><br>
Type (or select) Filename: <input type="file" name="uploadFile">
<input type="submit" value="Upload File">
</form>
</body>
</html>
 
OK!  That's a pretty basic form, but it's going to get the job done!  Now let's take a closer look at it.
First, notice that the action attribute of the form statement is going to cause the php page "getfile.php" to be called to process this form when the submit button is clicked.  (Also notice that we're using method="post", which we discussed in part four)
Next, in the form is an input type="file"   This provides a place for a filename to be typed and a "Browse" button which can be used as an alternative to typing the name, and opens up a dialog box which allows the user to select the file they wish to upload.  (Some browsers may provide a slightly different appearance for the input type="file" but the effect is still the same.)
Just to make things a little more self explanatory, we've changed the text on the submit button to read "Upload File".  That should be clear enough!
 
Processing the Form
Now we need to process the form, so we must create our "getfile.php" page.  Here we go:
<html>
<head>
<title>Process Uploaded File</title>
</head>
<body>
<?php
move_uploaded_file ($_FILES['uploadFile'] ['tmp_name'],
       "../uploads/{$_FILES['uploadFile'] ['name']}")
?>
</body>
</html>
 
This is the basics of getting the job done; we'll take a look at this first, then embellish it a little to make it more user friendly.  There's quite a lot of info to clarify about that one statement in there!
The statement uses the function "move_uploaded_file" which is a function built in to PHP.  When the file was uploaded, PHP created a temporary copy of the file, and built an array containing information about the file.  $_FILES is that array.
The move_uploaded_files function takes two parameters, seen here contained in parentheses and separated by a comma.  The first parameter tells the function where to get the file it is to move (copy), and the second tells it where to put the copy.
In the first parameter, we need the name of the temporary file that PHP created.  To get that, we reference the $_FILES array with associative indexes to the pieces of information we need.  "Huh?" you say!  Let me explain further!  The first associative index we need is to indicate which file we are talking about -- in our example here we only included one upload file, but our form could have had more than one input type="file".  To let PHP know which one we are dealing with, we use the name of the input field on the original form; in this case it was 'uploadFile'.  Next we refer to the 'tmp_name' associative index, which provides us with the name of the temporary file PHP created.
In the second parameter we similarly use the $_FILES array associated with our original input field name, but this time we reference the 'name' associative index.  This provides us with the original file name as it was on the user's computer.  By using "../uploads/" along with this reference, we tell the move_uploaded_file function to create a copy of the original file in a directory called "uploads" within the website, and to name the file with its original name.
Job done!
At least, we hope it is!  Things can go wrong when computers are involved, however.  I know -- that's tough for you to believe, right?   <g>   In the next part of this tutorial series, we'll embellish this example with tests for thing that can go wrong, code to handle those errors, and code to let our user know what's going on.

PHP Tutorial: File System

One of the most useful features of a server side language is its ability to interface with the file system on the server that hosts the website.  This feature clearly distinguishes the language from a client side language such as JavaScript.  While JavaScript is sent down to the client's browser and is then interpreted on their computer, server side languages such as PHP are interpreted and resolved on the server, and only the end result is sent down to the client's browser.  It is because of this fact that the language has the ability to interface with the files on the server.  PHP has the ability to work with both text files and sophisticated database systems.  This part of the tutorial discusses text files; we'll get into databases later.
To access a file you first have to establish a connection to that file.  This is done by opening the file with the fopen function.  To use the fopen function you provide it two parameters.  The first is the name of the file you wish to use and the second says how you want to use the file (for reading or writing, etc.)  Using the fopen function establishes a pointer to the file.  Here's an example:
<?php
$myfilepointer = fopen("myfilename.txt", "w");
?>
here, we're opening a file called "myfilename.txt" and saying that we wish to write to it.  The "w", which is what tells PHP we want to write to the file, is called the Access Mode.  Other values that can be used, and their meanings are:
r read only
r+ reading and writing
w write only & create the file if it doesn't exist
w+ reading and writing & create the file if it doesn't exist
a writing only, create if it doesn't exist, and place a file position pointer at the end of the file (appends records to an existing file)
a+ reading and writing, create if it doesn't exist and place file position pointer at the end of the file
These parameters have introduced the idea of a file position pointer.  As you read a file, something has to keep track of where you are in the file so that you can read the next record.  That something is the file position pointer.  This pointer gets interesting when you think about writing to the file.  If you are writing to a new file it's pretty straight forward -- you write a record, the pointer points at the end of that record and you write another record, and so on.  If, however, the file already exists and contains some records, the value of the pointer when you first open the file becomes very important!  If the file is opened with the pointer at the beginning of the file (like r+, w or w+), when you write to that file you will overwrite the existing records in the file, replacing them with your new records.  On the other hand, if you open it with the pointer pointing at the end of the file (like a or a+), you will append records to the file, adding them to the existing records.
Reading and Writing Records
Now that we have our file open, we need to read and/or write records.  This is accomplished with the fgets and fputs functions.

PHP Tutorial: Functions, Cont.

The usefulness of functions is greatly enhanced by the ability to pass information from the main body of code to the function and in the opposite direction, or between one function and another it is calling  Values that are sent to a function are called arguments.
Passing Argument to a Function
To define arguments that will be passed to a function, you provide a list of names for them between the parentheses in the function statement, like this:
function Myfunction ($arg1, $arg2)
and to pass values to the function as arguments by putting them between the parentheses following the function's name in the statement that calls it, like this:
$answer = Myfunction (3, 5)
I've used actual number here, but I could also have used variables.  There is something to watch out for with those variables!  Remember from the discussion about variables that variables have a scope?  This becomes very important here.  The function statement that defines a function is part of the function it defines; therefore variable defined in that same statement are also part of the function being defined; therefore their scope is local to the function.  This means that the variable's lifetime begins when the function starts to be processed and ends when the function ends.  Consequently, these variables are not available in the main body of code (or in the calling function, if this function is being called from within another function.)  Simply using the same name won't make it available!  In fact, using the same name in the main body of code will mean that you have two different variables with the same name.  This will not create an error, but it will certainly create a confusing program to work on!  It is best to use different names for the variables within your functions (another "be your own best friend" tip!)
Returning Results from a Function
A function returns a result to the calling code by using the "return: keyword, like this:
return $result;
When the return statement is processed, the function terminates and the value of the variable specified is returned to the calling code.  The return statement only returns one variable -- if you need to return more than one value, you'd have to define and return an array (we'll be getting into arrays a little later in this series.)
You could have more than one return statement in your function if, for example, you had conditional logic (such as "if" statements) within your function, but only one of them will ever be processed (since processing it terminates the function!)
An Example
Here's an example of a couple of variables being passed to a function as arguments with a result returned:
<html>
<head>
<title>Function Arguments Example</title>
</head>
<body>
<h1>Showing a Volume</h1>
<br />
<? php
function CalcVol ($x, $y, $z)
{
$vol = $x * $y * $z;
return $vol;
}
$long = 3;
$wide = 4;
$high = 5;
print  "The volume of this object is " . CalcVol($long, $wide, $high) . " volumetric units.";
?>
</body>
</html>
In this example you can see that a function called CalcVol is being defined, and that it receives three parameters, $x, $y & $z.  These are being used to specify the lengths of the three axes of a solid object, which the function multiplies together to determine the volume of the object.  The function then returns the volume to the calling code.
The function is being called from the middle of a print statement, which passes the three values contained in the variables $long, $wide & $high.  Thus the print statement will display the result of the calculation.
In the next part of this tutorial series, we'll take a look and some functions that are built in to PHP and at some more sophisticated ways to manipulate data being passed back and forth.

PHP Tutorial: Passing Data

The usefulness of functions is greatly enhanced by the ability to pass information from the main body of code to the function and in the opposite direction, or between one function and another it is calling  Values that are sent to a function are called arguments.
Passing Argument to a Function
To define arguments that will be passed to a function, you provide a list of names for them between the parentheses in the function statement, like this:
function Myfunction ($arg1, $arg2)
and to pass values to the function as arguments by putting them between the parentheses following the function's name in the statement that calls it, like this:
$answer = Myfunction (3, 5)
I've used actual number here, but I could also have used variables.  There is something to watch out for with those variables!  Remember from the discussion about variables that variables have a scope?  This becomes very important here.  The function statement that defines a function is part of the function it defines; therefore variable defined in that same statement are also part of the function being defined; therefore their scope is local to the function.  This means that the variable's lifetime begins when the function starts to be processed and ends when the function ends.  Consequently, these variables are not available in the main body of code (or in the calling function, if this function is being called from within another function.)  Simply using the same name won't make it available!  In fact, using the same name in the main body of code will mean that you have two different variables with the same name.  This will not create an error, but it will certainly create a confusing program to work on!  It is best to use different names for the variables within your functions (another "be your own best friend" tip!)
Returning Results from a Function
A function returns a result to the calling code by using the "return: keyword, like this:
return $result;
When the return statement is processed, the function terminates and the value of the variable specified is returned to the calling code.  The return statement only returns one variable -- if you need to return more than one value, you'd have to define and return an array (we'll be getting into arrays a little later in this series.)
You could have more than one return statement in your function if, for example, you had conditional logic (such as "if" statements) within your function, but only one of them will ever be processed (since processing it terminates the function!)
An Example
Here's an example of a couple of variables being passed to a function as arguments with a result returned:
<html>
<head>
<title>Function Arguments Example</title>
</head>
<body>
<h1>Showing a Volume</h1>
<br />
<?php
function CalcVol ($x, $y, $z)
{
$vol = $x * $y * $z;
return $vol;
}
$long = 3;
$wide = 4;
$high = 5;
print  "The volume of this object is " . CalcVol($long, $wide, $high) . " volumetric units.";
?>
</body>
</html>
In this example you can see that a function called CalcVol is being defined, and that it receives three parameters, $x, $y & $z.  These are being used to specify the lengths of the three axes of a solid object, which the function multiplies together to determine the volume of the object.  The function then returns the volume to the calling code.
The function is being called from the middle of a print statement, which passes the three values contained in the variables $long, $wide & $high.  Thus the print statement will display the result of the calculation.
In the next part of this tutorial series, we'll take a look and some functions that are built in to PHP and at some more sophisticated ways to manipulate data being passed back and forth.

PHP Tutorial: Functions

What is a Function?

In the last part of this tutorial series we looked at controlling logic flow in PHP.  This included logic flowing in a linear fashion, but with loops of logic at various points and with decision making along the way.  The overall flow was a straight line - the loops were processed where they occurred, and the logic continued along its line from the beginning of the program routine to its end.  There are times, however, when a series of instructions has to be repeated from a variety of different points within the main routine, or where a series of instructions needs to be followed that doesn't really fit within the main routine.  This all sounds horribly complicated -- let's see if a real world example will clarify the picture!
Suppose, for the moment, you have a bunch of freshly washed laundry, some had to be hung on a clothes line, some was dried in the drier.  Now it all has to be put away.  Some of the items have to be folded, some ironed and some hung on hangers.  First we need a set of instructions for removing the items from the clothes line, next a set for the drier.  As each item is removed from either source, we have to decide ("if" instructions, possibly?) whether the item needs to be folded, ironed or hung.  Then we need a set of instructions for each of these operations -- folding, ironing and hanging.  The processes (folding, ironing and hanging) are the same whether the item was removed from the clothes line or the drier.  Consequently, we can use the same folding, ironing and hanging routines whether we are calling them from the "remove from the clothes line" process or the "remove from the drier" process.
OK! Let's break it down!  (And you thought you knew how to do the laundry!)  First, our main routine is going to have two primary sections -- one for the clothes line and one for the drier. As an item is removed, we have to decide whether it should be folded, ironed or hanged, and process it accordingly.   Let's say that we know what "remove" means.  This allows us to say something like this (by the way, this kind of representation of what a program is to do is called "pseudocode" and is one of the most valuable tools available to a designer  -- beginner or seasoned expert alike!) ( let me repeat myself -- one of THE MOST VALUABLE TOOLS!!  Different software engineers use different styles of pseudocode, but pretty much any experienced one of them could understand any style.):
While (laundry still on the line)
{
  remove item from the line;
  { if (to be folded)
       {process folding-routine}
    elseif (to be ironed)
            {process ironing routine}
         else
            {process hanging routine}
  }
}
While (laundry still in the drier)
{
 remove item from the drier;
  { if (to be folded)
       {process folding-routine}
    elseif (to be ironed)
            {process ironing routine}
         else
            {process hanging routine}
  }
}
This isn't exactly PHP code, but it sure represents the way it can be coded!  (By the way, again, a seasoned programmer would instantly see that this routine can be consolidated once again -- do you see it?)  The interesting point for our purpose in this tutorial is that it illustrates what PHP calls a "function".  A function is a routine (or more accurately, a sub-routine) that can be called to perform its duties from any point in the program that needs it.  Here's the nitty-gritty of using a function in PHP:
 
Defining a Function
No rocket science here! -- Simply tell PHP we're talking about a function, give it a name, follow it with ( ) (that's the part the gets closer to rocket science -- more on that later) and specify the instructions it contains.  Like this:
function HangLaundry( )
{ instructions go here, between the braces }
Here we've defined a function called "HangLaundry".  Function names are case sensitive, meaning that HangLaundry is not the same as hanglaundry.  Personally, I like to capitalize each word in the name so that it is easier to read (remember the part about being your own best friend?)   The instructions contained within a function are not processed (executed) until the function is called, regardless or where within your program the function is defined.  This means that theoretically, your functions could be defined anywhere within the program.  Best practice, however, is to define all your functions at the beginning of your program script.  Again, you'll thank yourself later.
 
Calling a Function
A function is called by its name followed by a set of parentheses, like this:
if ($process = = "hang")
 {
    HangLaundry ( )
 }
This codes checks the value of a variable called $process and if it contains "hang", calls the HangLaundry function.
 
Variable Scope and Lifetime
It's important to note that if you define a variable within a function, that variable is only available within that function; it cannot be referenced in another function or in the main body of your program code.  This is known as a variable's scope.  The scope of a variable defined within a function is confined to that function -- in other words, it's local to that function.
If a function needs to use a variable that is defined in the main body of the program, it must reference it using the "global keyword, like this:
function AddingNumbers ( )
{
   global $sum = 2 + 2
 }
$sum = 0
Addnumbers ( )
print "2 + 2 = ".$sum
While the scope of a variable defined in a function is local to that function, a variable defined in the main body of code has a global scope.  The "global" keyword tells PHP to look for a variable that has been defined outside the function.
There is also the idea of a lifetime for a variable.  A variable defined within a PHP program script exists only while that script is running.  When the script ends, the variable ceases to exist.  This seems pretty obvious!  Now apply it to a function:  a variable defined within a function exists only while that function is being processed; when the function ends, the variable ceases to exist.    Ooooh!  Aaaah- yes!!
 
There are also other ways to pass information back and forth between the main body of code and the functions it calls (and also, since a function can also be called from within another function, between one function and another.)  I told you we'd talk about that set of parentheses later -- we'll talk about them next!

Comments

Comments areas are wonderful for making notes within your coding no matter what language you are currently using. It helps you organize your coding for editing or reading purposes. Comment areas are not "seen" visibly on the web page. They are simply coding notes.

There are two different types of comment tags. One type will comment out a single line of coding, the other will comment out a block of coding lines.

Single lines of coding may be commented using two slashes // or using a hash # symbol. This type of commenting may be used to comment out a full line, or the remainder of a line.


<?php

// This is an example of commenting.

# This is also an example of commenting.

echo "This text will appear on the web page. <br />";

// echo "This text will not appear.";

echo "Some more example text."; // That prints, not this.

?>

Outcome :
This text will appear on the web page.
Some more example text.

Commenting more than one line of coding is done using /* and */. Everything between these two tags will be commented. They can be used on a single line to many lines.

<?php

echo "This is a commenting test below. <br />";

/*
echo "This text will not appear.";
echo "Neither will this.";

*/

echo "This is a commenting test above.";

?>

This is a commenting test below.
This is a commenting test above.

PHP Tutorial: Logic Flow.

Controlling the flow of logic is a fundamental part of any program, including a PHP script, but what does the phrase actually mean?  Logic flow refers to the decision making process whereby you choose which actions to take under which circumstances.  Now let's say that is ordinary English!
Think for the moment of the process of filling a bath tub with water.  Here's a (greatly) simplified version of the decision making process involved:
  • Put some water in
  • Check the depth
    • Deep enough then quit
    • Not deep enough continue
  • Check the temperature
    • Too hot, then add some cold water and go back to "Check the depth"
    • Too cold, then add some hot water and go back to "Check the depth"
  • Add more water
  • Go back to "Check the depth"
This process illustrate the basic elements, or building blocks, of logic flow.  It has a start point, with an initialization routine (Put some water in.)  It continues with a cyclical routine, or loop, that is processed again and again until a certain condition is met.  This loop begins with "Check the depth", which is both the marker for the beginning of the loop, and the test for whether or not the whole process should be concluded.  The loop contains another condition test (Check the temperature) and three different process branches that are processed based on whether the temperature was too  hot, too cold or just right.  Each of these process branches returns to the beginning of the loop and the conclusion of the branch.
These fundamental building blocks are common to most programming languages, and vary mostly by the form of how they are implemented.  Here's how they are used in PHP:
The If Statement
The basic decision making statement, the "if" statement says "if this is true, do this, else do that".  Its format is like this:
if ( condition )
{ do these instructions }
else
{ do these instructions }
and here's an example:
if ($age < 21)
{ print "Minor"; }
else
{ print "Adult"; }
It is also possible to add a condition to the "else" side by using "elseif" like this:
if ($temp > $idealtemp)
{ print "Add cold water" }
elseif ($temp < $idealtemp)
{ print "Add hot water" }
else
{ print "Add more water" }

The For loop
You can create a loop by using a "for" loop construct (as it is known.)  The "for" statement says "for a value of x starting here, until the value of x meets this condition, and changing the value of x by this amount each time you process the loop, process this code".  This could use a little explanation!  Basically, x is going to serve as a counter.  We give x a start value, for example 1.  Then we specify a condition to test before we decide to process the block of instructions in the loop, for example x < 11.  Finally, we specify an amount by which to change x at the end of processing the block of instructions, for example, increment by 1.  In this example, the code would be run ten times, with x having a value of 1 the first time through, 2 the second, etc. The last time through it would have a value of 10.  Here's its format:
for ( counter's initial valuecounter's condition test, counter's increment )
{ do these instructions }
and here's an example
for ($count = 1; $count < 11; $count++ )
{
   $tot = 2 * $count;
   print "2 times $count equals $tot ";
}
This example prints out the two times table from two times one to two times ten.  It's worth taking special note of the fact that the test comes at the beginning of the loop -- that is, before the code block is run.  Hence the need for a test for "less than 11" in order to get the tenth iteration to run.

The "While" loop
Another loop construct is the "While" loop construct.  The for loop uses a counter to control the number of iterations of its code block, but the while loop can use any kind of condition.   There is an inherent danger here!  What happens if the condition always remains true?  The code never stops running -- that's what!  This is known as an infinite loop and the a sure sign of a programmer error.  PHP allows a system administrator to defend their system against this kind of abuse of processor time by providing a time-out mechanism.  PHP scripts are typically limited to 30 seconds of execution time, and will quit with an error at that point.  It is an important part of the debugging process to ensure that you don't wind up with any infinite loops!  That having been said.....
A "while" statement says "while this condition is true, process this code" and its format is:
while ( condition )
{ do these instructions }
Here's our two times table as a while loop:
$count = 1
while ( $count < 11 )
{
   $tot = 2 * $count;
   print "2 times $count equals $tot ";
   $count = $count + 1;
}
There is a couple of things to take particular notice of in this example.  Firstly, we had to include a separate statement to initialize the count data element because it is not part of the construct as it would be in a for statement.  Remember that the condition in a while statement can be any condition -- I have used a counter type of condition only to show the comparison of this construct to the for construct.  Secondly, and for the same reason, there has to be a statement in the code block to increment $count (I could also have used   $count++   or   $count += 1  -- I like the format I used the best because it seems the clearest to me.)
There is also a variant of the while loop that puts the test for the condition at the end, that is, after the code block has been processed.  This, of course, means that the code block will always run at least once.   This variant is the "do... while" loop and it says "do this code block, and while this condition is true, go back and do it again".  Its format is:
do
{ these instructions
}
while ( condition );
Here's our two times table as a do while loop:
$count = 1
do
{
   $tot = 2 * $count;
   print "2 times $count equals $tot ";
   $count = $count + 1;
}
while ( $count < 11 )
These options show you how you can create program execution loops in you PHP code.  Which one is the best to use depends on the particular type of execution requirement.  You have to think a it about the flow of logic as you see it, and use the construct that most closely resembles what you need.  Another thing to remember is that you can nest these constructs, by which I mean that the code block to be run by the construct could include another loop construct.  Any type of loop can be contained within any other type of loop.
When you include code within a loop like this it is a valuable thing to do to indent the code a couple of spaces like I have done in the examples above.  This is especially true when you include one loop inside another.  By the time you are two or three levels deep it is only the indentation that will show you whether or not you are missing any closing races!!  Remember that you really want to be your own best friend!