Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

As stated earlier, session identifiers are sent by cookies, but a browser may refuse them.
As a backup, you may use the SID constant. It will contain a string consisting of the
session name, an equal sign, and the session identifier. This is suitable for placing in a
URL, as I have done in both the form action and the anchor tag below it. If the browser
returns a session cookie to the script, the SID constant will be empty.


All the session functions are described in Chapter 8.


The include and require Functions


The include and require functions take the path to a file. The file is parsed as if it were
a stand-alone PHP script. This is similar to the include directive in C and the require
directive in Perl. There is a subtle difference between the two functions. When the
require function is processed, it is replaced with the file it points to. The include
function acts more like a function call.


The difference is most dramatic inside a loop. Imagine having three files you wanted to
execute one after the other. You could put an include inside a for loop, and if the files
were named something like include1.php, include2.php, and include3.php, you
would have no problem. You could just build the name based on a counter variable.


If you used require, however, you would execute the first file three times. That's
because on the first time through the loop, the call to require would be replaced with the
contents of the file. As I said, the difference is subtle but can be very dramatic.


Listings 7.7 and 7.8 show one possible use of the include function. Here we revisit an
example from the chapter on arrays. I've taken the definition of the array from the main
file and put it into its own file. All the code that matches ways to refer to months with a
preferred output form is not necessarily interesting to the main script. It is enough to
know that we've included the translation array. This makes the script in Listing 7.8 a lot
easier to understand.


This strategy of modularization will enhance the readability of your code. It gives the
reader a high-level view. If more detail is needed, it takes a few clicks to open the
included file. But more than enhancing readability, coding in this way tends to help you
write reusable code. Today you may use the translation array for a catalog request form,
but in a week you may need it for displaying data from a legacy database. Instead of
cutting out the array definition, you can simply copy the file.


Listing 7.7 Included File


<?
/*
* Build array for referencing months
/
$monthName = array(

Free download pdf