Chapter 6. Server Side Scripting

This chapter covers one of the most important topics in Web programming for those who plan to create easy-to-update sites, with dynamic content or interactive possibilities. Interaction with visitors includes the ability to offer shopping carts, vote in polls, or comment on blogs, all key parts of today’s Web commerce paradigm.

Server side scripting is the ability to provide scripts to the server that it can run, in the same way that the browser can run client side scripts, to generate HTML or XML pages. Generally, the use of server side scripting is limited to these two formats, although there are libraries available that will generate other artifacts such as images or sound.

Unlike with client side scripting, the end user (visitor) never sees the code that generates the pages, so it is a useful technique if there are proprietary techniques or technologies that the Web programmer would not want to share with anyone else. All that is delivered to the browser is the result of executing the script.

In addition, the server side script also has access to all the resources on the server—databases, email, plain text files, and so on—which means that it can do a lot of local processing before proceeding to deliver the results to the browser. There will be some restrictions as to what is available locally, but you need to check with your Web host to see what those restrictions are.

The server side scripting market is quite crowded, with four main contenders:

  • Server Side JavaScript

  • PHP

  • Perl

  • Active Server Pages (ASP)

Before I start explaining why I chose PHP, it is worth spending a little time examining the other three, for the sake of completeness. There is no question of bias, but there isn’t space in a book of this nature to look at all the possible options, and one had to be chosen that was most fit for the purpose of the Just Enough Web programmer.

Take Server Side JavaScript, for example. This does not yet have wide enough acceptances among the free, budget, and even medium priced Web hosts running Linux. Therefore, clever and reusable though the technology might be (after all, the book spends a whole chapter on JavaScript), the popularity of PHP means that it seems to be more widely available at the time of writing.

Plus, most Open Source server side software packages (such as WordPress and other popular content-management systems) are available in PHP. It is, therefore, well worth your time to get to know it a bit better.

Perl is an extremely powerful extraction and reporting language. It has a C-like syntax, which is very similar to JavaScript in some ways, but which also has the power of regular built-in expressions. This facility enables you to build quite convoluted expressions that are evaluated in a number of ways.

This ability makes Perl a good choice for the experienced coder, but for a beginner, it can make the scripts hard to read, write, and debug. Some would argue that there is no need to understand regular expressions to program in Perl, but because many of the modules that you’re likely to want to reuse will be written by professional programmers, not understanding them will make it difficult to learn from code that has been downloaded.

Active Server Pages were originally based on Microsoft’s Visual Basic language. This makes it a great choice for those who had already had an exposure to VB or VBScript (for browsers). With the move to ASP.Net, Microsoft opened up the languages to include most of those supported by the .Net environment, which made ASP.Net even more flexible. However, it is also a proprietary environment, and as such is not available as Open Source.

Furthermore, the price of hosting for ASP-enabled servers, running Windows, makes them prohibitive for Web programmers who are just starting out. This, combined with the commercial aspects of ASP, makes it unsuitable for discussion here. However, it is an excellent server side solution for Microsoft developers.

Which brings the topic to PHP. PHP is Open Source, has a very wide community following, is based on C styled scripting, and looks and feels vaguely familiar. It is also object oriented (or at least can behave in an object oriented fashion), meaning that Web programmers can play around with their own defined objects as if they were part of the language, which makes life much easier.

PHP also has the support of the hosting community, so any free or budget Linux host will likely support it, and there are even Windows builds available for those wanting to use that particular platform. It can connect to MySQL (a Web database, which you learn about in the next chapter) and comes with libraries for processing XML.

Above all, many if not all of the leading CMSs are written in PHP or have a PHP interface, from WordPress to Drupal, Joomla, and PHP-Nuke. These you’ll look at in Chapter 8.

For all of these reasons, Web programmers should at least become conversant with the basic ins and outs of PHP and keep a handy bookmark to this chapter for reference when they encounter something that they do not understand. Also, being aware of the capabilities is as important as being able to read the code—so that if Web programmers find that they need to achieve a given goal, they can work out how, in theory, it should be achieved before using this chapter to look up the actual solution.

PHP Programming

This chapter references PHP 5, although no PHP 5 specific functions have been referenced explicitly. There is always a PHP 4 version of any function or language feature that is discussed here available to those restricted by this version.

Given the acceptance of PHP as a reasonably standard platform, there is also reason to strongly suspect that future releases will remain fairly backwards compatible, too, as one can never be sure, in this Open Source world, what version will be running at any one time.

PHP is used as a pre-processor. This means that it is the server has to invoke the PHP software that is installed on the server when serving the page. The PHP software then interprets the various statements that are in PHP script and ignores everything else, passing any output back to the Web server, which forwards it in an appropriate manner to the client.

These PHP scripts are written in plain text, making them easy to edit and upload to the server. Although they can be compiled (which is programmer-speak for turning them into machine code), this is not common for user-created scripts. Most of the modules, which provide additional functionality beyond the core language, are compiled from PHP scripts.

Like JavaScript, PHP can be contained inline within an HTML document, or it can be referenced from an HTML document, usually through embedded PHP code. HTML and PHP can be freely mixed so long as the conventions are followed.

The difference is that all pages that contain PHP code should have the extension. php, so that the system can send them to the pre-processor. In addition, they will probably need to have their permissions changed so that they are classified as executable. Please refer to your Web host’s documentation or support forum for more details on this aspect of managing the PHP scripts.

Inline PHP

Inline PHP code can be put in an otherwise normal HTML file, which follows the usual structure, but contains, in places, specially quoted code. The correct way to break out of HTML and introduce some PHP is as follows:

<body>
<b>This is HTML.</b>
<?php
// PHP code here
?>
<b>This is also HTML.</b>
</body>

The server evaluates the PHP code by passing it to the pre-processor, which allows the programmer to write PHP code that can create HTML statements. This uses one of the built-in features of PHP, the echo statement. An example of this is as follows:

<?php
echo "<b>Bold Text</b>";
?>

Because PHP has constructs for selective, repetitive, and conditional processing, this means that you can create blocks of code that generate HTML on the same basis. So, for example, you can choose the background color of a document based on input from the user, if you wanted to.

Note that all of this effort will be for naught if PHP is not installed on the server. In this case, one of two things will happen. The PHP code might be identified by the server as text and returned to the browser as a page of text, thereby exposing the PHP code.

The more likely outcome, in modern server environments, is that the server returns an error page, as it is not sure what to do with the PHP file, having only been set up to serve HTML, images, and some other forms of files.

There is a third option, and that is that the server treats the PHP code as a proprietary object, and the browser starts to download it by asking the user to specify the location for the .php file. Clearly none of the three outcomes is desirable, so you’ll have to verify that your host supports PHP if you want to make the most of this chapter.

Like JavaScript, the convention is that all PHP lines must be terminated by a semicolon (;), although in some cases it can be omitted. Because the rules as to when this is the case are reasonably complex, it is better just to assume that every statement that is complete has to be terminated in this way.

Unlike client side scripting, the HTML code is delivered to the browser, because it is the server that evaluates the file. This means that when users select View Source from the menu, all they see is the resulting HTML code. This keeps the PHP source hidden, but does introduce an issue when trying to locate problems.

Therefore, it is going to be easier for the developer to correctly indent any HTML code that is generated. Otherwise, finding issues in a file of generated HTML will be nearly impossible.

Indentation can be introduced just by using space characters, and lines can be broken by using the special character. This might need some explanation, so consider the following PHP fragment:

<?php
echo "<table>";
echo "<tr>";
echo "<td>Table content</td>";
echo "</tr>";
echo "</table>";
?>

You might hope that this code would generate:

<table>
<tr>
<td>Table content</td>
</tr>
</table>

However, what the PHP fragment actually creates is all on a single line:

<table><tr><td>Table content</td></tr></table>

Now, if you are debugging a single line, this does not matter so much. But the chances are that a PHP file will generate HTML over several lines—perhaps as many as 100. If it is all concatenated in this way, it will become unreadable.

To break it up, you can use the following PHP:

<?php
echo "<table>
";
echo "<tr>
";
echo "<td>Table content</td>
";
echo "</tr>
";
echo "</table>
";
?>

This result is easy to read as PHP, and also generates HTML that is equally easy to read.

All kinds of code can be generated inline in this way; for example:

  • Conditionally included external script files (such as .js, .css, and so on)

  • JavaScript

  • HTML

  • CSS statements

Of course, PHP files can also be used externally and imported into PHP scripts, and there are a variety of ways to achieve this result.

External PHP

The easiest way to reference an external PHP file is through the include function, and is usually inserted in a block of PHP code. For example:

<?php
  include 'my_module.php';
?>

From the point that it has been included, the code is treated as if it were part of the underlying code file. Other files can also be included from the included file as well, so that an entire application can be built and included in a single line of code.

This mechanism is often used by content-management systems (such as Drupal, Nuke, Joomla, and others) to include variables that can be set by the programmer. These variables communicate certain settings to the underlying system, allowing for easy configuration just by altering a set of variables in an included file.

The advantage is that the programmers can create their own include file to contain the relevant variables, and it can be included after the defaults to overwrite the pre-selected values. Keeping the variables together means that they do not have to be repeated for each PHP script that uses them—they can just be included by filename whenever they are required.

There is also a function require(module) offered by the PHP language itself. This is identical to the include statement, with one difference. If there is an error in loading and executing the script, it will halt the script at that point with an error. The include statement just produces an error in such cases, and execution of the rest of the calling script continues nonetheless.

Both of the approaches also have a _once() variation. For example:

include_once 'my_module.php';

or

require_once 'my_module.php';

These variations could equally well have been written with quotes or parentheses and double or single quotes enclosing the string containing the name of the module. So, the following are equally valid:

include_once "my_module.php";

or

require_once ('my_module.php'),

or

require ("my_module.php");

The _once() variations are for use when the programmer wants the file to be included (evaluated) only once for the execution of a script. So, even when it is included multiple times from different scripts, all called from the main script, it will be evaluated only once.

Preventing the reevaluation means that any variables set are kept for the duration of the script’s execution, and if they are changed, they will not be reset. This mechanism is useful when multiple scripts share the same base set of functions and/or variables.

General Concepts

Before looking at the parts of PHP that make it truly useful as a language, you first need to understand some general concepts that you’ll see in the various illustrative examples that make up the discussion of the more complex topics.

Readers who have made it through the client side scripting discussions will find the terminology familiar. Those who have not might like to take a moment to go to the beginning of Chapter 5 and read about variables, types, loops, and conditional structures so that you’re familiar with the basics of programming.

As a reminder:

  • Variables are places to store information.

  • Each variable has a type associated with it that limits what can be stored in it and how it is processed.

  • Decision structures are based around conditions that evaluate to true or false.

  • Loops allow the programmers to repeat a specific set of instructions a given number of times or until a predefined condition is reached.

Bearing this in mind, there are some essential underlying basic concepts that you should understand before proceeding to the main programming part of the chapter.

Types and Variables

The PHP language supports eight primitive types—four scalar, two compound, and one special value, with some overlap between the mathematical types (hence there are really only seven discrete data types, but eight identifiers). A scalar type can contain one value for a (possibly infinite) set of allowed values.

PHP treats strings as scalar types, because arrays are defined as compound types, which contain elements of differing types. So, a compound type can use a single variable to refer to an object that has components that have a variety of individual types—an address might contain a street number and a street name, for example.

The four scalar types are as follows:

  • boolean

  • integer

  • float (also called a double)

  • string

The following sections discuss each of these types in detail.

boolean

This is the same as a Boolean value in any other language, except that must be written as either TRUE or FALSE, in capital letters. PHP is fairly type-insensitive and will quite freely convert a boolean from TRUE to 1 and FALSE to 0. In addition, FALSE can be equated with empty strings and arrays.

integer

Any 32-bit number can be stored in an integer, giving a large scope of values, both positive and negative. There is no unsigned version, so there will be an architecture-dependent limit on the size of value that can be stored there.

Integers can be cast from floating point numbers, but this will cause the result to be rounded down to the lowest integer value. The round() function is available to round the cast properly. This would be necessary when rounding the result of an integer division:

$one = 1;
$two = 2;
$my_result = $one / $two; // == 0.5
echo (int) $my_result; // 0
echo round ($my_result); // 1

The reason for the cast is that there is no integer division in PHP, so the result is always a floating point number.

float (also called a double)

These are equivalent in PHP, and can store a precision of roughly 14 digits, as in the IEEE standard for 64-bin floating point number representation. You can use the usual mathematical operators with both floating point and integer numbers, as you would expect.

string

The PHP string is a very important data type, as it is used for a variety of purposes. A string can be created by placing single or double quotes around it, for example:

$my_string = "hello";
$my_other_string = 'goodbye';

On the face of it, these two are functionally equivalent. However, singly quoted strings do not allow for escaping of special characters, including (carriage return) or (tab). Doubly quoted strings, however, allow for this, and subsequently, they are converted properly. In such cases, a double quote may be escaped (") to be displayed as part of a string. For example:

$my_string = ""hello""; // "hello"
$my_other_string = '"goodbye"'; // "goodbye"

The reason that the second line does not work as expected is that singly quoted strings accept escaping of characters. Doubly quoted strings also allow for expansion of variables inline. So, for example:

$my_substring = "green";
$my_string = "The color is $my_substring.";
              // The color is green

This would not be possible using a singly quoted string. There is also a final way to populate strings, using the heredoc operator, denoted by <<<. For example, to assign a chunk of text:

$my_string <<<EOD
This all goes into
my string.
EOD;

The heredoc behaves the same as if it were assigning a string in double quotes; therefore, it allows variable expansion and quoted characters. So, the variables can be embedded in the usual way.

Conversion to numbers from strings is automatic, but the reverse is not true. To do this, the strval($value) function must be used, which will return an appropriate string for the $value offered.

Finally, to concatenate two strings, the . operator must be used, which can be combined with the assignment operator to split a concatenation over several operations. For example:

$end = "the" . " " . "end";
$my_string = "The beginning ...";
$my_string .= "..."; // The beginning ... ...
$my_string .= "... the" . $end;
              // The beginning ... ... ... the the end

Other handy string operators and functions can be found in the PHP short reference section of this chapter.

The two compound types are as follows:

  • array

  • object

array

Unlike other languages, an array in PHP is stored as a map of data, which includes the possibility to store arrays of arrays, where each map has a key and a value. Simple arrays with no keys are also possible, but an array of characters does not equate to a string as it does in so many other languages.

So, the following will create a simple array;

$my_numbers = array (1, 3, 5, 7, 9);

Notice in this example that the array object constructor is used to build the type, which is not necessary for scalar types. The array is, as usual, indexed on zero, so accessing the first element can be done with:

$first_number = $my_numbers[0];

Here, notice the usual [] notation for accessing elements in the array. Of course, variables that resolve to a valid index can also be used to return the value stored at that index.

This is especially useful when creating maps of values. This is highlighted when the following code is considered:

$my_pie_recipe =
  array ("meat" => "chicken", "vegetable"
  => "potato", "serves" => 4);

This code creates an array that contains three values, each indexed by a key. Instead of returning a value using a zero-based index, you can now write code such as:

echo "Pie with meat will be a " .
           $my_pie_recipe['meat'] . " pie.";

This code will output the following:

Pie with meat will be a chicken pie.

In itself, this is not staggering. However, when combined with a variable, it means that you can construct code such as:

$pie_type = "meat";
echo "Pie with $pie_type will be a
     ".$my_pie_recipe[$pie_type] . " pie.";

The output of this code will be the same as before:

Pie with meat will be a chicken pie.

However, if you want to print out the recipe for the vegetable pie, all you need to do is change the $pie_type variable to access the array using a different key. In both cases the "serves" key remains completely independent of the other two. All the pies will serve exactly four people.

object

The object data type is assigned to a variable that is an instance of a class and is therefore classified as a compound data type. The concept of classes in PHP programming is a reasonably advanced topic and is discussed next.

Finally, there is the NULL data type that’s assigned to a variable that has had no value set or has had its value explicitly unset with the unset($variable) function. This is quite a special data type often used for testing when the result of an operation might be in question, and in database operations so indicate that no data is necessary for a given field.

All of these data types can be used to create variables of different kinds, for different uses. Some are defined for use by the system, and others can be set as constants. One set of such values are known as the superglobals, which are system predefined variables.

Predefined Variables

There is a set of predefined system variables that all start with the identifier $_ and are used to store system values. These are often referred to as the superglobals, and are available to all scripts running under the PHP processor.

A global variable is available to all code within a certain scope, usually after it has been defined in a given script. The superglobals do not have to be explicitly included in this way—they are always available.

The most important for the Web programmer are the following predefined variables that allow communication with the Web browser, by way of the request that’s sent from the browser to the server. The three single most important ones are as follows:

$_GET

The result of a form’s GET request

$_POST

The result of a form’s POST request

$_COOKIE

Cookie data

You’ll learn about how to use these later on, but they are stored as arrays of key and value pairs which map on to the form or cookie that has been used to store and/or submit the data. So, if you have a form that is designed to create a search query, using the HTTP GET request, you can use the following to extract the term:

$query = $_GET['q'];

This snippet assumes that the URL that referenced it was:

http://myserver.com/search.php?q=search+text

If the search text was submitted through a POST request, you could use the companion array key:

$query = $_POST['q'];

You’ll look at these in more detail later on, along with cookie processing.

User-Defined Variables

User-defined variables are all those variables that the programmer deems as necessary to store the data required to process the scripts. Each one has a name and a value and a specific set of rule governing exactly how the name should look.

A variable is declared upon use, or possibly prepared before needed, at the top of the PHP code. Variable names can start with a letter or underscore and can contain letters, numbers, or more underscores. They cannot start with a number or include any other punctuation than an underscore. Furthermore, variable names are case-sensitive and must be declared and used by prefixing the variable name by a dollar sign. This keeps them separate from other pieces of PHP code. So, to define a string, you might use code such as the following:

$my_string = "some string data";
$my_123 = 123;
$my_floating_double = 23.456;

You can also define variables as pointing to existing named variables by prefixing them with an & sign. This creates a reference to the existing variable through another variable, meaning that they both end up pointing to the same value in memory. This is coded as follows:

$pVariable = &$myVariable;
       // $pVariable points to $myVariable

If a value is assigned, using either of the variable names, the value in memory is altered directly (because one points to the other). Therefore:

$pVariable = "more string data";

echo "->" . $pVariable;
echo $myVariable;

This code will display "more string data" twice, because both $pVariable and $myVariable point to the same data (when combined with the preceding code snippet).

Variables are said to be in scope when they can be accessed by PHP code. This is generally dictated by the order at which the lines are executed by the PHP processor, so a file that is included at the top of the PHP code and sets a global variable will make that variable available to the rest of the lines that follow it, even if they are from different included scripts.

However, variables inside functions (named blocks of code) stay local to those functions and cannot be accessed outside, and also mask any global variables that have been set. So, for example, the following code will not do exactly what the programmer might expect:

$my_text = "test this";
function myFunction () { // defines a function
  $my_text = "test_that";
  echo $my_text . "
";
}
echo $my_text;

The output of this is as follows:

test that
test this

The $my_text variable has been masked inside the function myFunction by the local variable with the same name. The way around this is to use the global keyword to denote that the programmer understands that the variables he or she wants to access are global. This tells PHP that when the name is used, it is the global variable that you want to access and not any local ones.

Of course, the local variables then become masked, so ideally different names should be used for global variables, such as $g_my_text rather than $my_text. Alternatively, of course, function names could be attached to local variables to set them apart from any global variables, such as $myFunction_my_text, for example.

Constants

A constant is a value that cannot be changed in the PHP script, once the value has been assigned to the named variable. The value is available to the code only after it has been declared.

The naming conventions for constants are the same as for variables. A good programming convention to follow is to use uppercase names to separate the constants from the other variables visually.

This is why superglobals are denoted in this way—$_GET, for example—because it sets them apart.

Constants are also always global and can be accessed by any part of the script. However, they are limited to containing values that must be one of the built-in scalar types—Boolean, number, and string.

Constants are declared by using the define keyword, as follows:

define ("MY_CONSTANT", "the value");
define ("MY_NUMBER", 42);

The other thing that sets the constants apart from regular variables is that they do not have a dollar prefix. So, to use the constant defined previously in a piece of PHP code, you can use the following code:

echo MY_CONSTANT;

Constants are useful when creating code that needs values that can be changed according to a specific installation—for example, in a blog system, the default number of posts to display per page might be five. Rather than using a global variable to store this, and having to include the appropriate file, the programmer might decide to define a constant to store the value instead.

Classes

Classes are self-contained object templates that contain the data definition and method implementation that processes that data. The array data type is an example of a class and is instantiated by calling something called the class constructor.

Classes are good for modularity because they allow programmers to encapsulate the behavior and data into a single place that can be easily interfaced with. This also helps to make the code that accesses that functionality cleaner.

A class can be defined using the following skeleton:

class name
{
  var member;

  function name() // constructor
  {
    // Instantiate the object
  }
  function method()
  {
    // Operate on the object, perhaps return a value
  }
}

If this appears in a PHP file, you can use the following PHP code to instantiate it and access the method that it defines:

$variable = new name();
name->method();

Naturally, wherever there is a name in italics, the programmer should substitute his or her own identifiers. So, to create an object that is designed to represent, for example, an Amazon.com product, you might create a class as follows:

class AmazonProduct
{
   var $ASIN;
   
   function AmazonProduct ($ASIN_in) // constructor
   {
     // Instantiate the object
     $this->ASIN = $ASIN_in;
   }
  
  function MakeLink ()
  {
     // Operate on the object, perhaps return a value
     // The following is entirely fictional,
     // for illustration only!
     $link = "http://www.amazon.com/books
                   /$this->ASIN/aff=12345";
     return "<a href=$link>$this-7gt;ASIN</a>";
  }
}

Note that access to the member variables is achieved through the this variable, which is treated as a variable name in itself. This negates the need to prefix the variable with a dollar sign, as the whole stanza this->member is treated as the variable.

To use this class, programmers have to allocate it to a variable:

$my_book = new AmazonProduct ("1598636847");

From this point on, whenever programmers need to insert a link to the product whose ASIN is 1598636847, they can do so with a simple call to the MakeLink member function:

echo $my_book->MakeLink();

You’ll see the various ways in which functions can be defined in more detail later on. Each one is just a block of named code that can be specified once and called multiple times with different sets of data to operate on.

One final note is that the programmer can only break the class definition into multiple code blocks if that is done within a method definition. This is to allow the programmer to break out of a method to use plain HTML code and then step back into the class to finish off the definition.

It is also possible to access the properties of a class from outside it; however, in the interests of modularity, I would argue that this should be kept to a minimum. Nevertheless, the same arrowed notation can be used, as follows:

echo $my_book->ASIN;

This line of code would simply output the ASIN of the $my_book object.

Clearly, if this was to be allowed between method definitions, it would be at a time when there is no executable code being evaluated, and the result would not be coherent. For example, this is perfectly allowable:

<?php
class myClass {
// there is no executable code here
  function myClassFunction () {
  ?> <!–out of php code–>
     <b>This is executed in myClassFunction</b>
  <?php // back in again
  }
}
?>

In this code, when myClass->myClassFunction() is called, the only thing it will do is generate the bold line of text. This illustrates the power of jumping in and out of inline PHP within a class definition, but it is also to be used with care because it is easy to lose track of the script when moving in and out of PHP code and HTML.

Operators

The PHP language has the usual complement of comparison, mathematical, and logical operators, plus a few special ones for processing strings and arrays. You can use an operator to compare two PHP expressions or to combine them. Some of those combinations result in a modification of the operands (the variables on the left or right of the operator).

Expressions that are built up using operators can also be grouped by using parentheses to override the orders of precedence built into the language. As a rule of thumb it is always better to write:

$var = ($a + $b)–($c * ($d / $e));

rather than:

$var = $a + $b - $c * $d / $e;

Even if the programmer knows that the two expressions should evaluate to the same final value, using parentheses makes sure that there are no misconceptions and also improves the debugging (error fixing) rounds.

Comparison

The PHP language supports the usual collection of comparison operators that you can use with the basic built-in scalar types except the string. This limits their use to numbers and the Boolean data types. Of those, only the simple tests for equality can be used with both numbers and Booleans.

The basic equality test is the familiar ==, which can be used to test for equality of two expressions, which can be built up from multiple PHP elements. The result of the comparison is true if both sides of the operator are equal. For example:

var_dump(1 == 1); // prints true
var_dump(0 == 1); // prints false
$one = 2;
var_dump($one == 1); // prints false

The companion operator, !=, tests for inequality. It returns true when both of the expressions are not equal and false otherwise. So, for example:

var_dump ("1" != 1); // prints false after conversion to number
var_dump ($one != 1); // prints true, see above

For all numerical types (and in some cases the other types, but that is subject to a set of complex rules for internal type conversion), the following comparison operators are also allowed:

a < b

Is a less than b?

a > b

Is a greater than b?

a <= b

Is a less than or equal to b?

a >= b

Is a greater than or equal to b?

The PHP processor will convert values according to its own logic. So, strings provided for comparison will be converted to numbers and compared accordingly. If a string contains no numerical data, the chances are that it will be converted to zero.

Similarly, the comparison of a float and an integer will return TRUE only if both are identical, so no rounding will take place. Bearing these rules in mind, you’re well advised to do any type conversions explicitly, to avoid any assumptions creating invalid logic in the scripted code.

Mathematical and Logical

The set of mathematical operators includes the usual range of familiar operations:

+

Add

*

Multiply

/

Divide

-

Subtract

These can be used with any numerical data types, although there are some special meanings that these operators take on when they are combined with other data types, as you’ll see shortly. Recall that when types are mixed, PHP makes some of its own decisions when it comes to producing a compatible result.

For the sake of a quick reminder:

$var_result =3/2;

The result of this code is automatically assigned to a floating point value that’s placed into $var_result, thus making the data type of that variable into a floating point representation, regardless of what it might have been before. It can be cast to an integer by using the cast mechanism:

$var_int_result = (int) 3 / 2;

However, because it will be rounded down due to PHP’s cast mechanism, the resulting value will be 1. To get the correct value (1.5, rounded to 2), it is necessary to use the round() function:

$var_int_result = round (3 / 2);

Note that the round() function does not need to be cast to an integer, because that is the value that it returns, nor does the value passed to the function need to be cast in any way.

Apart from this minor curio, the mathematical operators work in exactly the fashion that is expected. The operators can also be combined with the assignment operator (=) to assign the result to a variable. Some examples of this are as follows:

$result = 0;
$result += 3; // $result = $result + 3
$result /= 2; // $result = $result / 2
$result *= 3; // $result = $result * 3
$operand = 4;
$result -= $operand * 5;// $result = $result - 4 * 5

Many programmers will find it easier to debug code where the fully expanded version of these operations has been used, but the previous method is a useful shorthand in many cases. In addition, you can use the + and - operators in conjunction with a variable as a post-increment or decrement operation.

For example, the post-decrement operator looks like the following:

$result++; // $result + = 1 or $result = $result + 1

This point applies equally to the - operator, which performs a decrement rather than an increment. The other mathematical operators cannot be used in the same way.

The logical operators are as follows:

&&

and

Returns true if both operands are true

||

or

Returns true if one or the other or both operands are true

n/a

xor

Returns true if one or the other of the operands are true

!

not

Returns true when the operand is false, false otherwise

These operators all take two operands, except the not operator, which simply inverts the Boolean value of the expression to which it relates. Each of the operands must be a Boolean value, which usually means that it is the result of a comparison, contained in parentheses to ease readability.

For example:

($a == $b) && ($c == $d)   true when all are equal

Each of the operands can also be used as the symbol or keyword variant, so || is functionally equivalent to or. There is no such symbol equivalent for xor, which is different from other languages which use the ^ symbol.

The result of the operations can also be assigned to a variable, which will take the Boolean data type upon assignation. For example:

$result = true && false;
$result = ($a == $b) || ($b >= $c);

In the first example, $result would become equal to false, and in the second, if $a is equal to $b or if $b is greater than or equal to $c, $result will be assigned the value true. These can take some getting used to, but they are very useful.

String and Array

String operations come in two flavors—assignment and concatenation. There are other functions for operating on strings, but using these is more complex than just applying an operator. As you’ve seen before, assignment works for both singly and doubly quoted strings:

$string_one = "a string
";
$string_two = 'another string';

You can concatenate these two by using a fragment such as:

$string_three = $string_one . $string_two;

This will result in $string_three taking the result of the concatenation—"a string another string". However, in the final result, the two parts will be separated by a carriage return as a result of the expansion of the escape sequence .

Arrays can also be used with the operators that are usually reserved for mathematical comparisons and assignments; however, they take on a slightly different meaning. Not all of the mathematical symbols have an equivalent, and there are also a whole range of other array processing functions which you’ll read about later in the chapter.

This chapter won’t look at all the possibilities, because most of them simply aren’t useful to the Just Enough programmer. The first is the == equality operator, which will return true if the two arrays have the same key/value pairs, in any order.

For example:

$array_a = array (1 => "One", 2 => "Two", 3 => "Three");
$array_b = array (1 => "one", 2 => "three", 3 => "two");
$array_c = array (2 => "Two", 1 => "One", 3 => "Three");
var_dump ($array_a == $array_b); // false
var_dump ($array_a == $array_c); // true

The reason that $array_a and $array_c are considered to be equal is because they contain the same key/value pairs, even though they are not in the same order. In order to test for absolute equality, you use the identity comparison operator, ===.

With this in mind, if you repeat the last comparison using this operator, you get a different value:

var_dump ($array_a === $array_c); // false

This operator also has a companion, the non-identity comparison, !==, which tests for the opposite. Therefore, placing this in the previous statement, you arrive at:

var_dump ($array_a !== $array_c); // true

Naturally, there is also the inequality operator, !=, which performs the reverse check to the equality operator. Again, if you apply this to the previous example:

var_dump ($array_a != $array_b); // true
var_dump ($array_a != $array_c); // false

Like some other languages, but unlike C and JavaScript, PHP also allows you to use the greater and less than signs together to perform the inequality test:

var_dump ($array_a <> $array_b); // true
var_dump ($array_a <> $array_c); // false

So, the operators are not dissimilar in many ways, except that the array complicates the comparison process somewhat by containing a map of data. Obviously, the same process works for arrays that are not organized into a map, too.

Flow Control

One of the most important parts of any programming language, as you are by now aware, is the possibility to change the flow of the execution around the script. This allows you to conditionally include piece of code and repeat certain sections.

For example, if a list of blog entries contains some categories that should not be displayed, you might want to process each one, one at a time, and only display certain entries in the resulting page. This requires a loop to go through each entry and a decision to print the entry conditionally based on the result of a comparison operation.

To do the latter, you use decision making, and there are a variety of constructs to facilitate this.

Decision Making

As with JavaScript, the basic decision-making unit is the if construct. This can be a simple case of testing a single condition, as the following shows:

if ($blog_entry->category == 1) {
   // print blog entry
}

Deconstructing the previous code, note that the code that you want to execute if the condition evaluates to true is contained in braces { and }. In the bracketed condition part, you can use any valid PHP expression that evaluates to true.

In case you need to provide an alternative operation to the one that was intended when the condition is met, the else construct can be added:

if ($blog_entry->category == 1) {
   // print blog entry
}
else {
  // do something else
}

In this snippet, if the condition is not met, the contents of the else construct will be executed. There is an alternative notation for the else statement, born out of the need to break out of PHP occasionally. The generic form for this notation is as follows:

if (condition) : some code
else : some other code
endif;

Clearly this method is just a template, and you need to embellish it with actual PHP code, but it quickly becomes quite complex:

if ($blog_entry->category = = 1) : $blog_entry->display();
else : $blog_entry->show_link();
endif;

So far, so good. However, the main reason for the new notation is to ease the possibility to break out of the PHP. In order to add the HTML that will embellish the result of the supposed $blog_entry object member functions, you can construct code such as:

<?php if ($blog_entry->category = = 1) : ?>
Blog entry title : <?php $blog_entry->display(); ?>
<?php else : ?>
Blog link to alternative : <?php $blog_entry->show_link();
endif; ?>

More alternatives can be added to the basic if .. else construct by introducing the elseif keyword. This allows you to test a second (third, fourth, and so on) condition within the same decision block. For example:

<?php
if ($blog_entry->category = = 1) {
   // category 1 logo
?>
<img src="logo_1.gif">
<?php
}
elseif ($blog_entry->category = = 2) {
  // category 2 logo
?>
<img src="logo_2.gif"7gt;
<?php
}
else {
  // default logo
?>
<img src="logo_default.gif">
<?php
}
?>

(Note that the logo_default.gif file should be present in the same folder as the PHP code in order for it to work properly.)

You can use this code example with the alternative construction as well by following the same approach as before. Note that this code breaks out of the PHP script to write the image tag straight in as HTML rather than using an echo statement from the PHP code itself.

The other kind of decision-making construct that PHP offers should also be familiar to you, and is the switch construct, which is used to avoid endless if, elseif, else nesting. If you put this into the same logic as the previous code, you see the obvious advantage of using the switch construct:

switch ($blog_entry->category) {
case 1 :
  echo "<img src="logo_1.gif">";
  break;
case 2 :
  echo "<img src="logo_2.gif">";
  break;
default :
  echo "<img src="logo_default.gif">";
  break;
}

As in other languages, such as JavaScript, the break keyword stops the evaluation and breaks out of the switch construct. Again, the default clause produces a result when the other statements all evaluate to false.

Unlike in other languages, the switch .. case construct can test a variety of data types, including numbers and, interestingly, strings.

Looping

If you need to construct a block of code that is to be executed a number of times, PHP gives you several alternatives. The first is the basic while loop, with the evaluation of the termination condition at the top of the loop:

while ($blog_entry->category = =1){
   // do something
   $blog_entry = $blog_list[$entry++]; // get the next one
}

This construct is accompanied by a version that uses the alternative notation that you have encountered in the previous section. This looks akin to the following:

while ($blog_entry->category == 1):

  // do something
  $blog_entry = $blog_list[$entry++]; // get the next one
endwhile;

Note that I have added the endwhile keyword to the end of the loop to show PHP where I would like it to end. In either case, you can break out of the PHP in the usual manner, using the <?php and ?> notation in order to mix in HTML code.

The alternative to the while loop is the do .. while loop. Here, the evaluation is performed at the end of the loop:

do {
   // do something
   $blog_entry = $blog_list[$entry++]; // get the next one
} while ($blog_entry->category == 1);

The key difference between the two is that the loop will execute at least once in the do .. while loop, whereas it might not execute at all in the while loop where the evaluation is done at the top of the loop construct. Another difference is that the do .. while loop cannot be constructed using the alternative notation for other flow control code blocks.

The last kind of looping mechanism you are going to look at is the for loop. This comes in two different flavors, each providing for the alternative notation as well as the standard usage with braces. The generic for statement allows initialization, comparison, and alteration clauses:

for ($entry = 0; $entry < count($blog_list); $entry++) {
   // process entries
}

This snippet uses the count() function to check that the for loop only executes as many times as there are elements in the $blog_list array. The alternative notation follows the same general form as the previous constructs:

for ($entry = 0; $entry < count($blog_list); $entry++) :
 // process entries
endfor;

There is also a simpler way to process items that are part of a collection, such as an array, by using the foreach construct. This assigns a value to a temporary variable that is placed in the foreach statement as follows:

foreach ($blog_list as $blog_entry) {

 // process entries
}

This block is functionally equivalent to the while and for loop constructs already discussed, but without the $entry counter to index into the array. The alternative notation for the foreach construct is as follows:

foreach ($blog_list as $blog_entry) :
  // do things
endforeach;

Finally, there are two important keywords for use with loops—break and continue. The break keyword works in the same way for loops as it does for the switch construct; it breaks out of the loop without completing processing. You can use this to exit the loop prematurely when a specific condition is met.

The continue keyword is similar in a way, except that it does not break out of the loop, but moves to the next iteration. So, if there is a specific entry that you do not want to process, you can skip an iteration. The code for this might look something like this:

foreach ($blog_list as $blog_entry) {
  if ($blog_entry->category != 1) {
     continue; // we don't process these
  }
  // process entries
}

Although the foreach loop was used to illustrate the continue keyword, it can be used with any of the previous loops, as can the break keyword. With these looping capabilities, you can build any data processing model.

Functions

A function is a named block of code that can be called, with or without parameters, from a piece of PHP code once the function has been defined. These functions can also return values.

The first thing to note is that function names are not case-sensitive. This is different from the rest of the PHP syntax and also most other programming languages. However, it will make programming and maintaining scripts easier if function names are treated as if they are case-sensitive.

The scope of functions is global once the function has been defined, and this means that if it is conditionally defined, using an if construct or similar, it is accessible only once the condition has been satisfied and the function has been evaluated. If the code never gets executed, the function will never be defined and hence will never exist.

If you remember that all PHP scripts are evaluated in a top-down fashion, and on demand as they are required, this means that, potentially, some functions will never be executed.

This is a little counter-intuitive, especially when you consider that functions are available from anywhere after the point at which they were defined. This also extends to functions that are defined inside another function.

Subsequently, you have to be very careful about naming functions correctly so that if a module is used that comes from the outside, it is useful to have a function list so that different identifiers are used. When you design code that’s to be made available for wider use, it is also useful to include some kind of function identifier to keep the names unique.

An example of a simple function that takes a parameter and returns a value is as follows:

function getBold ($text)
{
  return "<b>$text</b>";
}

Of course, functions can be defined that do not accept a value or return one. In the former case, this just means that the function name is followed by parentheses that are empty. If no value is returned, the only difference is that the return keyword is not used.

In addition, you can define functions that have a default in case the programmer using the function is not passing a value for some reason. To do this, the first line (where the definition is established) is as follows:

function getBold ($text = "")

Function parameters can be passed by reference or by value. Passing by value means that if a variable is passed in the parameter list, it cannot be changed by the function. To pass by reference, which will allow these changes, all that you need to do is put a & in front of the variable name in the function definition:

function makeBold (&$text) // Pass by reference
{

  // function code
  $text = "<b>$text</b>";
}
// more code here
$myText = "Title Text";
makeBold ($myText);
echo $myText;

Before you develop your own functions to perform specific processing, first read through the section entitled “PHP Short Function Reference,” which covers the most useful of the functions provided by PHP to help you achieve your programming goals.

There is no sense trying to reinvent the wheel, and the community support of PHP as a Web language is such that virtually every function imaginable has already been thought of, and most of them have been implemented.

PHP Short Function Reference

This section is a not a complete reference guide to PHP, but it covers, in a compact fashion, the available functions and common extensions that you will encounter when building your Web applications.

In particular, it is a good handy reference to have when you’re reading the remainder of the book, which shows you how these technologies are applied in real applications. Many of the examples that are presented in future chapters draw on the knowledge contained in this short reference guide.

Common Modules and Functions

There are over 150 common modules and functions listed in the PHP manual, and the vast majority of these are available in default binary builds, or in PHP processors that have been built from scratch by Web host providers. Luckily, knowledge of these is based on a need-to-know model—if you need it, look it up.

However, there is a set of core libraries that contain some vital extensions to the basic PHP library for manipulating data types, as well as some extensions that can be compiled into the main PHP processor and offer key external functionality, such as the ability to connect to a MySQL database.

Without going into too much detail, it is better to have these compiled into the environment, because to have to run an external PHP script every time a core library or extension has to be accessed would not be very efficient. These things are also so fundamental to PHP programming and understanding PHP code that you will encounter (and perhaps want to extend) that they are worthy of closer examination here.

Core Libraries

Some parts of the PHP system are actually libraries that extend the core functionality of the language. So, for example, all the array manipulation functions (those that are prefixed by array_) are part of the core libraries and not the language itself.

In addition, there is a collection of functions for manipulating arrays (count, sort, in_array, current, next, and so on) that are listed in the function reference and that are part of the libraries and not the PHP language proper.

Array functions include anything listed as array_ plus a collection of non-prefixed array manipulation functions such as count, sort, in_array, current, next, prev, reset, and end.

Class functions include class_exists and other functions that get information about a specific class and are also extensions to the core language. These functions very useful for object oriented or modular programming. The class library includes the core language constructs for creating classes.

Date and time functions, including functions for manipulating date information, are also part of the core libraries

Finally, there is a set of DOM functions that allow the handling of HTML and XML documents, both local and remote, using a well-defined API. These functions are very easy to use for basic tag extraction, for example, or when creating/validating XML feeds.

This is not an exhaustive list, but gives an overview of the most common core libraries and the ones that are used most frequently in PHP programming. In addition to the libraries, there is also a set of extensions that can be compiled into the language when it is activated within an environment.

Unlike the core libraries, the extensions might not be available from one provider to another.

Compiled-In Extensions

The php_info() command shows what options have been compiled in. It can be used in a simple PHP script to display the various libraries that are available. Be warned, however, that it can lead to a rather long document being displayed in the browser window.

However, the alternative is to use the function_exists(function) command, which returns true if a given function is available. Of course, by this point in the script it may be too late, but it will at least give the possibility to choose between possible graceful exits or alternative solutions.

The MySQL database extension is a common one and is used here for databaseing and so I have listed it in the function reference.

Function Reference

The following is not exhaustive. It is, however, a summary of the functions that you’ll encounter when you read and write PHP code. Some of the more esoteric functions in each class have been left out: the chances are that if you need an esoteric function, you are experienced enough to know that it exists.

The functions are broken into functional areas:

  • Core functions

  • Math functions

  • Variables and classes

  • Strings

  • Arrays

  • Web- and browser-related functions

  • MySQL functions

The last two areas pertain particularly to Web programming and will provide vital information that is built on in the “Examples” section of this chapter as well as in future chapters when you start gluing all the pieces together and making Web applications.

Core Functions

These functions perform useful tasks related to built-in features of the PHP programming language and do not have a specific entry in the sections that follow. They will probably crop up in many projects that you put together, either from components created by other people or from your own coded solutions.

The first two are system functions—eval and die.

eval

The eval function takes a string and evaluates it is if it were PHP code:

eval("$my_var = "a string");
echo $my_var;

This code will output "a string". The $my_var variable had not existed until the eval function was called. The return value from eval is always set to null unless the code in the evaluation part returns a value, in which case the return value is passed back as the eval return value.

die

The die function is used to do two things:

  • Print an error message

  • Halt the script

When die is encountered, no more processing will take place, and the error message passed to the function (if any) will be displayed. An example is as follows:

if (not_logged_in($user)) {
   die ("Error : $user not logged in.");
}

As you’ll see in the “Examples” section, die is generally used to catch system errors such as the inability to connect to a database.

unset

The unset function unsets a variable and sets it to null.

getdate

The getdate function returns an array that contains several key/ value pairs, representing the current date/time at the server:

mday

From 1 to 31 (day of the month)

wday

From 0 to 6 (Sunday to Saturday)

mon

Numeric month of year, 1 to 12

month

Textual equivalent of mon, January to December

year

The year, in four-digit format; that is, 2008

yday

The day of the year, zero-based

hours

The hour component of the current time, 0 to 23

minutes

The minute component of the current time, 0 to 59

seconds

The second component of the current time, 0 to 59

Each of these key/value pairs can be accessed through its key:

$today_date = getdate();
echo "The month is $today_date['month'].";

For UNIX programmers, it is useful to know that an optional parameter can be supplied that must be the equivalent to the value returned by the time() function.

function_exists

The function_exists function tests to see whether a specific named function has been defined and implemented in the current scope. It is useful for testing, given a possible collection of equivalent routines, which is available for use or for making sure that the function that is about to be defined does not use a name that is already taken.

func_num_args

The func_num_args function returns the number of arguments that were passed to a function and must be called from within that function. For example:

function variable_argument_function () {
  $num_args = func_num_args();
  echo ("I was passed $num_args arguments.");
}
variable_argument_function ("banana", 1, 7);

The output from this code snippet will be:

I was passed 3 arguments.

This function can be combined with the func_get_arg function to process functions that accept variable argument lists.

func_get_arg

The func_get_arg, when passed an integer, will return the argument passed to the current function, indexed by that integer. To process a variable argument list, you could use code such as:

for ($index = 0; index < func_num_args(); index ++) {
   $arg = func_get_arg(index);
}

However, the limitation of this function is that it does not take into account the default arguments when a value has not been passed by the call to the function. Ordinarily, this should not matter.

func_get_args

The func_get_args function returns, as an array, the arguments that have been passed to the function containing the call. This allows you to simplify the previous code to use a foreach loop:

$arglist = func_get_args();
foreach ($arglist as $arg) {
  // process $arg
}

Like the other argument processing functions, it will generate a warning when not called from inside a function.

Math Functions

This section discusses a useful collection of functions that can be used with numbers. Unless otherwise noted, both integers and floating point number can be used as arguments.

max

Returns the highest of two values

min

Returns lowest of two values

Both the min and max functions accept two arguments and return one of them by value.

abs

Returns the absolute value of its argument

The abs function takes an argument and strips it of any negative sign, and is the equivalent to multiplying a negative number by –1.

sqrt

Returns the square root of a number

The sqrt function takes an integer or floating point number and returns its square root in the same data type as was supplied:

echo sqrt(9); // prints 3
echo sqrt(9.0); // prints 3.0

Previously, you had seen casting from floats to integers and learned that the system always rounds them down. However, there are also some specific functions for otherwise rounding and converting fractions to integers:

ceil

Rounds the supplied floating point number up

floor

Rounds the supplied floating point number down

round

Rounds the supplied floating point either up or down

fmod

Returns the floating point remainder (modulo) of a division

The key difference between the ceil, floor, and round functions is that the floating point argument supplied is usually rounded according to the standard that any value equal to or greater than 0.5 is rounded up. However, ceil would force 0.49 to be rounded up, and floor would force 0.51 to be rounded down:

$val_low = 9.51;
$val_hi = 9.49;
echo floor($val_low); // prints 9
echo ceil($val_hi); // prints 10
echo round($val_hi); // prints 9

The fmod function returns the remainder of a division. This is calculated as the value left over after the division has taken place, given that the division is expected to yield an integer (whole number) and a remainder. This is much easier to appreciate with an example:

$x = 5.7;
$y = 1.3;
$r = fmod ($x, $y); // remainder after x/y

In this example, $r will contain 0.5. The division of 5.7 by 1.3 yields 4.38. . ., which is rounded to 4. Next, 4 is multiplied by 1.3 to see what the result would be. This results in 5.2, which makes the remainder 0.5 (5.7–5.2).

There are also two functions for generating random numbers:

mt_rand

Generates a random number

mt_srand

Seeds the random number algorithm

The mt_srand function accepts a value to seed the generator with, but can be called without a parameter to generate its own seed. Once seeded, the mt_rand function can be called, with two parameters, indicating the minimum and maximum integers between which the value should be. So, to generate a random number between 1 and 100, you use this:

$echo mt_rand(1, 100);

Finally, the math library contains a whole collection of trigonometric functions. I’ll not explain what each one relates to here, because those using them will know what they are for and this is not the place for a mathematical discussion of trigonometry.

pi

The pi function simply returns the value of pi that is assigned to the constant M_PI. It is called as a function with no parameters.

cos, sin, and tan

These are the three main trigonometric functions, representing cosine, sine, and tangent functions. They are also available in arc and inverse flavors, which are denoted by an a prefix or h suffix, respectively. For example—asinh is the arc inverse of sin.

They all accept their parameters in radians and not degrees, but there are two functions to convert between degrees and radians:

deg2rad

Converts the parameter from degrees to radians

rad2deg

Converts the parameter from radians to degrees

Both of these functions accept functions that are floating point or integer values and will return a floating point value.

Variables and Classes

The following functions are useful in manipulating classes and variables that have been defined by the users in their PHP programs.

The first such function, class_exists, tests to see whether a given class has been defined. It is equivalent to the core function_exists function, except that it accepts a class and not a function name.

The get_object_vars function takes an object, being an instance of an existing class, and returns an array of key/value pairs representing the name of each property of that object and their associated value, if set. For example:

class weblog_entry {
  var $title, $content;

function weblog_entry () {
    $title = "";
    $content = "";
   }

function weblog_set_title ( $t ){
   $this->title = $t;
  }
}

From the previous code, you can instantiate a variable from the class definition and set the title as follows:

$entry = new weblog_entry();
$entry->weblog_set_title ("A Title");
$properties < get_object_vars ($entry);

The $properties variable now contains an array that has the following entries:

$properties['title']
$properties['content']

In case you need to see what the array contains and what the indexes are, you can use the var_dump function. This provides a human friendly dump of any complex type or PHP expression. It is used as follows:

var_dump ($properties);

The previous code will yield a display along the lines of:

Array
(
    [title] => A Title
    [content] =>
)

An even more useful function is the var_export function, which performs an export of the data in PHP format. This means that you could use the resulting strung to recreate the object. This can be used as follows:

$code = var_export ($properties, TRUE);
                          // return, don't print out
$code = "$my_array = " . $code; // prepend some more code
eval ($code); // run it by PHP

The result of the previous snippet will be that $my_array contains a copy of the structure and data from the $properties variable, itself derived from the weblog_entry class. The important point to note is that it is a snapshot of the actual content and can be recreated from the string that is returned through var_export by passing it to eval.

Strings

The following is a guide to the various functions that you can use to process strings. Only the most commonly used ones are detailed here. The most common, and the one that you have already seen in several occasions, is the echo function.

This function outputs a string, either with escaping and variable expansion (if double quoted) or without (if single quoted). Strings can be concatenated in the input stream, which might not be included in parentheses.

Valid examples are as follows:

echo "This is a string
";
echo 'this is a string
';
echo "this is " . " two strings";

To find out the length of a string, use the strlen function. It returns an integer indicating the number of characters in the string. A companion function, count_chars, returns more detailed information about a specific character occurrence.

The count_chars function takes a string as input and produces an array where each byte (character) that is in the string is the key, and the value is the number of times that that character appears in the string. The function also takes a second parameter, which modifies the result returned. The most useful values for this parameter are as follows:

1

Returns only those characters used

2

Returns all the characters not used (based on the ASCII values)

3 & 4

The same as 1 or 2, but with the result returned as a string

The following is a possible use for this function:

foreach (count_chars ("Hello World", 1)
                       as $letter => $freq) {
  echo $letter . " => " . $freq . "
";
}

This code would yield output similar to the following:

32 => 1
72 => 1
87 => 1
100 => 1
101 => 1
108 => 3
111 => 2
114 => 1

To convert the $letter values to characters that can be displayed, you can use the chr function, which takes an ASCII value in decimal format and returns the printable equivalent.

The explode function takes a string and breaks it up into an array of strings, based on the provided separator. So, the following would break a sentence into words:

$sentence = "the cat sat on the mat";
$word_array = explode (" ", $sentence);

The explode function could also be used to parse a CSV string:

$csv_row = "value, value, value";
$csv_array = explode (",", $csv_row);

The opposite of explode is implode, which takes the same arguments and returns a string as an array of separated values. So, to turn an array of values into a CSV string, you could use:

$csv_string = implode (",", $csv_array);

It is also possible to extract part of a string, if you know the start and length by using the substr function. This returns a value corresponding to the section of the string that has been indicated. For example:

$my_string = "Hello World";
echo substr($my_string, 4, 3); // prints o W

The final parameter is the length of string to extract, not the end index, and is optional; if it is missing, the whole string past the start point is taken. The start point is zero-based.

Trimming and Padding

There are a number of reasonably self-explanatory functions for removing or adding characters to strings. These should need very little explanation:

ltrim ($ string)

Removes whitespace from the left (start) of $string

rtrim($string)

Removes whitespace from the right (end) of $string

trim($string)

Removes whitespace from both sides of $string

One point to note is that each of these functions can be combined with a second parameter that will remove any character from a given set from the start or end (or both) of the string. The default is, as noted, whitespace.

A related function, str_pad, is used to pad a string with the contents of another string, which can be truncated if the final length would be greater than desired. The general form for str_pad is as follows:

str_pad ($input_string, $length, $pad_string, PAD_TYPE)

The function returns a string and does not modify the $input_string in any way. The $pad_string can be any sequence of characters. There are three possible values for PAD_TYPEPAD_LEFT, PAD_RIGHT, and PAD_BOTH.

Comparison and Searching

Beyond the operators that are used with strings, there are also some specific comparison functions that work in the same way as the C or JavaScript equivalents. For this reason, I don’t go into too much detail of them here.

The first function is strcmp and it returns 0 if two strings are equal, a value less than 0 if the first string is considered to be less than the second, and more than zero if the first string is considered to be greater than the second. strcmp takes two parameters—the strings to be compared.

To find the first occurrence of a substring in a string, you can use the strpos function, which takes a string and a substring, in that order. A third parameter can be added that specifies the offset at which to start the search. To start the search from the end of the string, you can use the strrpos function.

If an entire string rather than just a character is to be searched for, you can use the strstr function. This function will return the part of the string that contains the substring rather than the numeric position. If the index is required, a string can be supplied to strpos or strrpos instead. Some examples:

$big_string = "Hello World";
$substring = "orl";
echo strpos ($big_string, "H"); // prints 0
echo strrpos ($big_string, "o"); // prints 7
echo strstr ($big_string, $substring); // prints orld
echo strpos ($big_string, $substring); // prints 7

Similar to the strstr function, there is the substr_count function that counts the number of occurrences of a substring in a string and returns the numerical count. So, based on the previous strings, the following could be constructed:

echo substr_count ($big_string, "lo"); // prints 1

Finally, there are two functions for replacing portions of a string. Neither of them need to have search strings and replacement strings of the same length, so the final length of the string can change. In addition, both strings and arrays of strings can be supplied as text to search and replace, such that each is mapped on a one-to-one basis.

The str_replace function takes three parameters:

$search_for = "World";
$replace_with = "PHP";
$input = "Hello World";
$result = str_replace ( $search_for,
           $replace_with, $input_string );

The result from this example would be "Hello PHP". The first two parameters can also be arrays:

$search_for = array ("Hello", "World");
$replace_with = ("Greetings", "PHP");
$input = "Hello World";
$result = str_replace ( $search_for, $replace_with,
                        $input_string );

Now the result is "Greetings PHP". These two forms represent a very powerful search and replace function, but remember that the application of the function is overlapped on each iteration. This means that if the intermediate result contains a string that can also be subject to replacement, this will occur during the processing.

The following example is taken from the PHP documentation and illustrates this behavior:

// Outputs: apearpearle pear
$letters = array('a', 'p'),
$fruit = array('apple', 'pear'),
$text = 'a p';
$output = str_replace($letters, $fruit, $text);
echo $output;

There are other comparison and search and replace functions, but this discussion represents the most useful subset for the vast majority of operations.

HTML-Related Operations

There are a few useful functions that can help you when you’re writing PHP code that needs to process HTML. Besides the obvious function of breaking a document into tags (which you’ll read about later on), there is a set of functions that can process individual HTML strings.

The html_entity_decode function takes a string of HTML, with the various entities represented as coded values (for example, “being an encoding of”), and decodes them. Like many of the string-processing functions, it does not actually change the string but returns a new one.

Likewise, the htmlentities function scans a string for entities that ought to be encoded and provides a string with the relevant encodings performed. It is, in a sense, the opposite of the decode function.

The nl2br function takes a string that contains escaped newlines (that is, characters) and inserts a line break (HTML tag <br />) in front of them. This has the effect of breaking the lines in the resulting HTML where the original author expects them to be, based on their editing.

Finally, to remove any tags from a piece of HTML, you use the strip_tags function. This function will render a chunk of HTML (with or without <script>and <?php ?> tags), as plain text. Anything that would not be displayed is ignored (stripped out).

Miscellaneous Operations

There are a few string operations that didn’t seem to fit in anywhere else, so they are expanded here.

The str_shuffle function returns a randomly shuffled version of the original string. This might be useful in password generation, for example. A companion function, strrev, returns a reversed version of the string passed as a parameter. Finally, the two functions strtolower and strtoupper provide a way to change the case of a string. The strtolower function returns a string where all letters are converted to lowercase, and the strtoupper function returns one where all the letters are capitalized.

As a slight curio, the ucfirst and ucwords functions can convert the first letter of a string to uppercase or capitalize the first letter of each word, respectively. All of these functions receive a string and return the string with the modifications performed. Unless this result is assigned back to the string that is passed, the original is not affected.

Arrays

Although the basic array handling built into PHP that you have already seen is great for the majority of functions, there are some occasions when a little more power is needed. Luckily, PHP provides a whole suite of built-in functions to support complex array tasks.

There are many more than are strictly needed in a “Just Enough” programmer’s arsenal, but the following summarizes the most useful ones.

To find out how many items there are in an array, the count function is used. It can also be used to count the properties of an object instantiated as a variable based on a user-defined class. It generally takes one parameter and returns an integer, although there is the possibility to specify what mode to use when counting items.

Refer to the PHP documentation if you need more advanced control over the count mechanism.

An array can also be sorted, using the sort function. Sorting is performed in an alphabetical manner, which provides consistent results so long as the types of values in the array are not mixed. One caveat is that the array keys will be reassigned and not reordered, so if there is a logical mapping between the keys and values, this will be lost, because the array is sorted on the values.

To check for the existence of a value in an array, you can use the in_array function. Theparametersforthis,inorder,arethevalue to look for and the array to look in. This parameter ordering is different from that of some of the other search functions.

Another thing to watch out for is that it is case-sensitive and can be made type-sensitive by adding a third parameter, set to TRUE. This last parameter is not used often. The search is always case-sensitive. An example of the in_array function is as follows:

$my_array = array ("Top", "Middle", "Bottom");
if (in_array ("Middle", $my_array) {
  echo "Found the value!";
}

Note that the function returns a Boolean value. The companion function, which is used in the same way but which looks for a key in the array rather than a value, is the array_key_exists function. Aside from the fact that it looks at the key, the functionality is identical.

To obtain the key from an array that corresponds to a value (rather than just a true or false), you can use the array_search function. If a simple array is populated, rather than a key/value array, the index is returned. For example:

$my_array = array ("Top", "Middle", "Bottom");
if (in_array ("Middle", $my_array) {
  $index = array_search ("Middle", $my_array); // index = 1
}

You can use the array_merge function to merge a list of arrays, based on some simple rules. Generally, the second array is appended to the first array. If the indexes are numerical (simple arrays), no values are overwritten. However, if the indexes are user-defined (key/value pairs), any value in the first array having the same key as a value in the second array is overwritten. For example:

$array_1 = array (1, 2);
$array_2 = array ("one" => 1, "two" => 2);
$array_3 = array ("two" => 3, "one" => 4, 5);
$temp_array = array_merge ($array_1, $array_2);
print_r ($temp_array);

This yields the result:

Array
(
    [0] => 1
    [1] => 2
    [one] => 1
    [two] => 2
)

However, if you then merge in $array_3, as follows:

$temp_array = array_merge ($temp_array, $array_3);
print_r ($temp_array);

The final output is as follows:

Array
(
    [0] => 1
    [1] => 2
    [one] => 4
    [two] => 3
    [2] => 5
)

Note how the index continues, even when interlaced with other keys. PHP is not fussy about the kind of data or keys used to access it, so it is possible to iterate through a whole array of different types, using various keys to access the data.

A sub-array can be extracted from an array using the array_slice function. This has many wonderful options, which you can look up if you need them. The most useful form is as follows:

array_slice ($input_array, $position, $length)

When used with correct parameters, this form returns an array that represents a sub-array starting at the zero-indexed position $position and is of $length length. The original array is untouched.

The companion function, array_splice, accepts the same parameters, returns an array that represents the items to be extracted, and removes them from the array. If you need to provide a replacement set of values, you can indicate this in an optional fourth parameter. Otherwise, the parameter list is the same as the array_slice definition.

There is also a set of functions for adding and removing individual elements to and from an array. These are as follows:

array_push

Adds an element to the end of the array

array_pop

Removes the last element of the array

array_shift

Adds an element to the front of the array

array_unshift

Removes the first element of the array

The array_push and array_shift functions take the array to operate on and a value to add to it as parameters. The array_pop and array_unshift functions generally only take the array to operate on. Otherwise, the functionality is as expected from the descriptions.

The array_rand function returns the key for a random entry into the array. To shuffle contents at random, you can use the shuffle function. Both functions take the array variable as input parameter.

Finally, the array_diff function compares two arrays and returns an array that contains the difference. This has no effect on the contents of the two arrays passed as parameters. Multiple occurrences of the value are considered to be equal and the keys are ignored, so two identical values with different keys are considered to be the same and are not returned.

Web- and Browser-Related Functions

Before you learn about document-related functions, there are a few functions used to process URLs in a standard way that you should consider. The first is parse_url, which returns an array from an URL, where each element refers to one of the components in a standard URL. This only works for complete, fully specified URLs and will not work with relative URLs.

Thus, the following can be written:

$url_components = parse_url
     ("http://www.mysite.com/query.php?op=1");

The $url_components array will contain:

[scheme] => http.
[host] => www.mysite.com
[path] => /query.php
[query] => op=1

From here, the query would have to be split into another array using the explode function with the & as separator. Each string in the resulting array could also be exploded by passing the = as separator to yield the value pairs. It is easier to use the $_GET superglobal, however.

The urlencode and urldecode functions simulate passing data on the URL in the same way that form processing does. In other words, spaces are replaced by + signs, and other non-alphanumeric characters are replaced by encoded versions. Such an encoded string can then be decoded using the urldecode function.

SimpleXML

The SimpleXML class gives a very easy way to access XML documents that have a predefined structure that is known by the programmer. Actually, the class can parse any valid XML file, but for a number of reasons, it might not prove practical to navigate the resulting object tree if the structure is not known.

For example, SimpleXML can be cumbersome to use when processing XHTML files with varying internal structures.

A SimpleXML object can be instantiated from an XML file by calling the simplexml_load_file function. So, for example, you could load the XML feed from a Website with:

$xml = simplexml_load_file
            ('http://leckyt.wordpress.com/feed/'),

If you did not know the layout of this feed, the print_r function could be used to display it. The following shows the beginning of the resulting dump:

SimpleXMLElement Object
(
  [@attributes] => Array
  (
    [version] => 2.0
 )
  [channel] => SimpleXMLElement Object
  (
     [title] => Leckyt's Weblog
     [link] => http://leckyt.wordpress.com
     [description] => Just another WordPress.com weblog
     [pubDate] => Sun, 03 Feb 2008 13:57:02 +0000
     [generator] => http://wordpress.org/?v=MU
     [language] => en
     [item] => Array
     (
        [0] => SimpleXMLElement Object
             (
                 [title] => That tricky second post

The way that the XML is accessed is through the object tree. So, to return the value associated with the title of the first entry (it’s the last line in the previous dump), you can use a statement such as:

$entry_title = $xml->channel->item[0]->title;

You can probably appreciate the power of this approach, but also see the issue that it raises regarding navigation. Because the properties are filled out by name, it is difficult to navigate when you don’t know the names of the tags in the XML document.

You’ll look at one way of dealing with this later on in the book, but simply knowing that the object exists, knowing how to populate it, and knowing a few things about PHP is enough for most cases. For example, you can loop through the blog posts very easily:

foreach ($xml->channel>item as $entry) {
  echo "<b> $entry->title </b><br/7gt;";
}

Of course, the feed contains many other pieces of information that could be displayed as part of the previous loop. If you need more power to dig into the XML tree, you can use the following DOMDocument class instead.

DOMDocument

The DOMDocument offers a powerful front end to processing XML and HTML files. Like any library that is powerful, it is also complex, so I have tried to reduce it to its bare minimum and give just enough information so you can understand the examples later in the book and also use the DOMDocument in your own projects.

A new object is created in the same way as any other class:

$xml = new DOMDocument();

At this stage, it has no data. So, to load XML, you can call the loadFile method:

$xml->loadFile('http://leckyt.wordpress.com/feed/'),

Note

At this stage, it is worth noting that there is a companion loadHTMLFile function that loads an HTML rather than an XML file. Use this when the source is an HTML document (local or on the Web).

Unlike SimpleXML, the DOMDocument does not have a structure that can be output with print_r. Instead, you have to delve into the object tree using a couple of useful methods. The first, getElementById, assumes unique IDs are in force across an HTML or XML document, using source XHTML such as:

<div id="my_post">
</div>

With the XML tree, this is not true, so you use the getElementsByTagNamemethod, which returns all of the tags, and their contents, in an array. The code looks akin to the following:

$taglist = $xml->getElementsByTagName('item'),
                  // get all the items

This results in an array that’s a DOMNodeList object. Given that it is an array, the foreach method of accessing it works and it also has a length() member method. So, to get the number of objects in it, you can use code like this:

$taglist->length();

The object also has an item($index) method, which you use instead of the square bracket notation. To return the first entry in the blog list, use code such as the following:

$entry = $taglist->item(0);

The result of this operation is a DOMNode object. This has the following member methods:

->hasChildNodes()

Returns true when there are child nodes

->parentNode()

Returns the DOMNode that is the parent

->childNodes()

Returns a list of children

->previousSibling()

Returns the previous sibling of the same parent

->nextSibling()

Returns the next sibling of the same parent

All of these member methods allow you to traverse the object tree. However, to extract data from the current node, you can use the following:

->nodeName()

Returns the node’s name (item, in this case)

->nodeValue()

Returns the value

This last returns a whole slew of data, simply because the point at which you are in the tree as a result of all this is still a branch. The data that is required is in the title child of the current entry in the tag list. You could use the traversal functions to locate it, but it is easier just to call getElementByTagName again, but this time on the node that you have selected.

Finally, to do the same as the single SimpleXML line, to print the title, you have to traverse the whole structure. This yields the following result:

$item_list = $xml->getElementsByTagName('item'), // pick the items
$entry = $item_list->item(0); // select the first one
// find the entry that contains the title and print its value
$title = $entry->getElementsByTagName('title')->item(0)->nodeValue;

You can choose for yourself which of the two classes you use, but bear in mind that the DOMDocument approach has the key advantage that it can also process HTML, which means the previous approach makes slightly more sense.

Email

The last of the Web functions that you’ll look at concerns email. To send an email message, assuming that the Web host allows it, one simple call is all that is needed:

mail ($to, $subject, $message, $headers)

In this call, the $message must be delimited by a carriage return on an empty line. This could be written as follows:

$message = "Dear $user,
 Here is a test.

                        
Thanks,
Admin

";

The $to is a list of comma-separated email addresses, and the $subject is more or less open, within the relevant email specifications. The $headers are optional, but if you want to send HTML email, the appropriate MIME headers have to be set in this parameter. For example:

$headers = 'MIME-Version: 1.0' . "
";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "
";

The return value will be true if the mail could be sent.

MySQL Functions

There are many more functions than covered here. For example, the administrative functions have all been left out because the average readers are not going to be administrators of the database that they are connecting to.

The following is the bare minimum needed to get up and running with a MySQL installation, and more than enough to cope with all the examples that are used in this book. MySQL itself is dealt with in Chapter 7, “Web Databases.”

Note

As of PHP 5, the MySQL functions are installed by default. Previously, this was not the case, and they had to be enabled explicitly. However, there is always room for a specific host not to include them for a number of reasons. It is always best to check.

The first function used is one of the most complex, and it establishes a connection to a MySQL database system. It takes the following form:

$link = mysql_connect ($server, $username, $password);

The $server will be the name of the server that has been given by the Web host. Usually a value of localhost will work, or the IP address of the host in question. Your $username and $password are set when the individual database is set up—this is covered in Chapter 7.

To choose a database upon which to perform SQL queries, use mysql_select_db. It uses the $link passed back from the connection function. The general form for this is as follows:

mysql_select_db ($db_name, $link)

Assuming that the database name ($db_name) is correct, the return value from this function will be true. If it is false, there has been an error. The exact nature of an error on a MySQL function call can be determined using the mysql_error function, which returns a string containing the error details. For example:

mysql_select_db ($db_name, $link) or die mysql_error();

This example will print a simple error message if the selection of the database did not succeed. More detail would be user friendly, but this code will stop the processing and inform the users that an error has occurred.

The mysql_query function is used to execute any kind of SQL query on the database. Its general form is as follows:

$result = mysql_query ($query, $link)

The $link parameter is the same $link that was provided when the database was first opened. If only one connection has been made to the database, this can be omitted. If the query was a SELECT query (see Chapter 7), the results can be extracted one at a time from the result set using the mysql_result function. This has the general form:

$value = mysql_result ($result, $row_number , $field_number)

The $value that is returned is the cell that is referenced in the result set. If there was only one field selected, the $field_number parameter can be omitted.

If the query had an effect on the database (data was inserted, deleted, or modified, for example), you can use a separate function to determine how many rows were updated. The mysql_affected_rows function returns an integer representing this. It has the general form:

mysql_affected_rows ()

The function operates on the last query, regardless of how many links are open to the database. To find out how many rows were returned in a result set that is the result of a select style query, you use the mysql_num_rows function. Its general form is:

$num_rows = mysql_num_rows ($result)

Unlike mysql_affected_rows, mysql_num_rows is tied to a specific result set. Several result sets can be held in memory at one time, with different variables providing the link to the result set on the server.

A much better way to retrieve the results is to use the mysql_fetch_assoc function, which returns an array that contains all of the results in the next row of the result set. The general form is as follows:

$array = mysql_fetch_assoc ($result)

Each element can be accessed through the array by field name. Each time the function is executed, the internal row pointer moves one row through the result set. It can be reset or set to a specific index using the mysql_data_seek function:

mysql_data_seek ( $result, $index )

Finally, to close the database link and free up any pending resources, you use the mysql_close function. It has this general form:

mysql_close ($link)

It is good practice to do this when no more operations are foreseen on the database, but because establishing the link can take some time, it should not be done until the script has no more need for the database.

PHP Examples

The following two examples cover the three most used functions of PHP in Web programming projects—processing forms and cookies and accessing databases. The code does not show the only way to proceed to perform these functions, and in some cases it might not be the best way, but the solutions work as a kind of cookbook to help beginning Web programmers get started.

Form and Cookie Processing

Form processing is made very easy in PHP by the use of the two superglobals, $_GET and $_POST, which are arrays that contain the form data that has been submitted. If you’ve used JavaScript validation, that data will already be pre-validated, so processing it should be easy.

Assume the following HTML form:

<form action="/age.php" method="post">
Name : <input type="text" name="name"><br/>
Age : <input type="text" name="age"><br/>
<input type="submit" value="Go!">
</form>

The age.php script that is referred to in the form receives the data in the $_POST superglobal, because that is the method chosen for the form’s submission process. You can extract this data in a PHP document as follows:

Hi <?php echo htmlspecialchars($_POST['name']); ?>.
You are <?php echo (int)$_POST['age']; ?> years old.

The htmlspecialchars function ensures that all of the various special characters that the users could have entered are correctly displayed as HTML and not left raw. The cast in the second PHP snippet ensures that only a number is displayed.

If a URL is submitted that has been built by an affiliate (for example) and looks something like product.php?affid=123456&product=27, you can also use PHP’s own processing to extract the data.

However, the data values will be stored in the $_GET superglobal. Other than this, they are accessed in the same way.

Processing cookies is also almost as easy. The setcookie function is used to set a named cookie with a value. It’s best to address cookies as if they are all elements of an array called 'cookie'. The following examples are lifted from the PHP documentation:

<?php
// set the cookies

setcookie("cookie[three]", "cookiethree");
setcookie("cookie[two]", "cookietwo");
setcookie("cookie[one]", "cookieone");
?>

This code stores the cookies as an array that can be referenced like any other array, once it has been extracted from the $_COOKIE superglobal. Again, the following is lifted from the PHP manual:

<? // after the page reloads, print them out
if (isset($_COOKIE['cookie'])) {
     foreach ($_COOKIE['cookie'] as $name => $value) {
         echo "$name : $value <br />
";
     }
}
?>

Because the cookies have been set as, for example, cookie[one], the value can be accessed from the root identifier $_COOKIE['cookie']. You could equally have called them apple[a], apple[b], and apple[c], but this would have meant accessing them through $_COOKIE['apple'], which makes less sense.

Database Connectivity

The section on the PHP MySQL functions provided some basic information about the functions used to connect to a database. However, the code was not linked together in one coherent PHP example. The following is a complete example that shows elements of good programming practice as well as basic usage of MySQL database access.

First, you establish the link:

$link = mysql_connect('mysql_host', 'mysql_user',
                           'mysql_password')
    or die('Could not connect: ' . mysql_error());

Note that I have adjusted the die clause a little to be more informative for the end user. It is also possible to use this model to email the administrator or provide a link so that the end user can fill out a form and report the error.

With the $link in hand, you can go on to select a database to operate on:

mysql_select_db('my_database')
     or die('Could not select database'),

Again, the failure clause is handled better than in the previous section. Now, because you have not yet read about databases, the actual querying will not make much sense. However, in the spirit of completeness, here is the code to execute a query on the database:

$query = 'SELECT * FROM my_table';
$result = mysql_query($query) or die
           ('Query failed: ' . mysql_error());

Assuming that the code has progressed this far, you can now print out all the results of this query. Note that this could be quite extensive, so it is better to limit the resource usage in some way by not returning every row for the result set if it can be avoided.

The code to generate the HTML is as follows:

echo "<table>
";
while ($row = mysql_fetch_assoc($result)) {
    echo "	<tr>
";
    foreach ($row as $col) {
        echo "		<td>$col</td>
";
    }
    echo "	</tr>
";
}
echo "</table>
";

Note the PHP looping constructs that allow the programmer to test for the availability of rows and then loop through the columns. The model that is shown here can be reused for any kind of table.

Finally, you can close the connection, which is identical to the previous example but is mentioned here just for the sake of completeness.

mysql_close($link);

That is all that you need to know about the PHP facilities for SQL. However, the next chapter covers the actual database programming language—SQL—in more depth.

Recap

This chapter set out to give you the basic knowledge that you need to be able to create PHP scripts for use on your site. The features that you have examined here will give you enough information to create a small content-management system (when combined with a database), perform Web 2.0 RSS mashups (combinations of multiple existing technologies that create new platforms, technologies, or feature sets that transcend the existing ones; see Chapter 9 for more), and even create Websites that pull content from all over the Internet, using SimpleXML and DOMDocument with HTML.

The things to keep coming back to are the language constructs and function reference—these are the parts that are most easily forgotten. Above all, most of the learning that you’ll do will be in deploying your own solutions, usually based on someone else’s starting point. There’s nothing wrong with this, as long as you understand what it is you are doing.

Many of the concepts are also common to other kinds of Web programming and server side languages, so getting used to the way that the code is used is also part of the learning process. Before doing anything really useful, though, you have to learn a little about databases, and that is the topic of the next chapter.

 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.75.235