<? PHP Bits & Bolts ?>

PHP Language Fundamentals

PHP was designed to intercept the request for a web page, and process the page first in the PHP pre-processor, and then pass the adjusted page to the Apache server. If PHP does not see any PHP script tags, then the page is passed without interference to the server.  PHP pages must be run from a web server, and cannot be tested locally like a standard HTML page.

Not only must your PHP page be on a web server to run, but ALL requirements for a PHP page to run must be met. These may include:

  1. The web server must be configured to run PHP pages
  2. You must upload the file into the proper directory
  3. Your page may need to be error free, or the server may need to be enabled to display errors
  4. Your page must have the proper file extension (.php)

PHP can be installed on a Windows machine, and even be set up to run side by side with other types of server pages such as JSP or ASP. Most commonly, one server side language is featured.

PHP & Text

PHP can display HTML or any other type of text by using one of two (nearly) equivalent commands, print or echo:

<?php print "This is how I use the print command!"; ?>

PHP is almost entirely ignorant of HTML.  We provide the HTML expertise.  PHP will dutifully reproduce what is inside the double quotes above, and display it on an HTML page.  Note the semi-colon at the end of the command.  The semi-colon is like the period at the end of a sentence, and indicates a complete PHP statement.  Single quotes could have been used instead of double quotes in the above example.  It's recommended to use echo instead of print since echo is shorter to type, and in some is processed by PHP a bit faster.

Interspersing PHP & HTML

PHP code can be interspersed between sections of regular HTML. As long as the script tags are opened and closed properly, there is no conflict.

<div align="center"> <?php echo "Place some PHP here!"; ?> </div>

The rules of HTML & PHP must be applied in their respective areas.  Raw HTML can never go inside PHP tags.  However, with the print or echo command you can reproduce nearly any type of HTML:

<div align="center"> <?php print "<b>This is bold</b>"; ?> </div>

Escaping Characters

We can choose to use single quotes or double quotes to indicate our strings.  However, what if the character we choose to end the string shows up inside the string?  In that case we'll need to escape the violating character, which would otherwise cause an error:

<?php echo 'We have a customer named O'Malley'; ?>

Note the use of the backslash above, which is used to escape single quote character that immediately follows it.  This treats that character as part of the string, and not the end of it.  We can escape single quotes, double quotes and other special characters this way.

Single vs Double Quotes

Sometimes it's easier to choose single or double quotes.  If we find we are printing a lot of HTML, we could choose single quotes, since HTML attributes use a lot of double quotes:

<?php echo '<div align="center"><font color="red">This has double quotes!</font></div>'; ?>

 A developer can place large blocks multi-line text that start and end with a single quote:

singleQuotePrint.php View Code

 Double quotes will be handy when we write SQL to speak to the database, which identifies text (string) data with single quotes.

Variables

In order to make our pages dynamic, we'll store data in memory locations called variables.  The word 'variable' gets it's name from the root of the word 'vary' as in change.  Variables in PHP start with a dollar sign, and can store character data called strings:

$myName = 'Bill';
print "My name is: " . $myName;

In the above code the string "Bill" is placed into the variable named $myName.  In our code we'll place the name of the user to personalize our pages.  Eventually we'll store the name in a database, and deliver it to the page as a variable when required.  Note the 'dot', which connects, or concatenates (a fancier word with the same meaning) the variable to the string.

Short Tags

Every once in a while in a PHP page you'll see an equal sign, which is a short cut for displaying the contents of a simple variable interspersed with HTML:

<div align="center"><font color="red"><?=$myName;?></font></div>

While this saves quite a few keystrokes, and has an elegant look, the developers of PHP are considering deprecating (removing) support for short tags, so officially I'm discouraging the use of short tags.  If you find them in my code, I'll be replacing them.  However I completely agree with the following Short Tag Rant 

Constants

We can also store data in a structure similar to variables called constants.  These can be filled with data like strings or numbers, but when filled can't be changed.  This is why the structure is called a constant, because it's contents can be counted on to be consistent:

define("SALES_TAX",.089);
print "The rate of sales tax is currently " . SALES_TAX;

Unlike variables, constants do not use the dollar sign as an indicator.  However, they do start with an upper case letter, and as a convention are frequently all upper case, so they are easily identified.  One more big advantage of a constant is that constants are everywhere available in a PHP page, and are therefore global in scope.  Variables are not global in scope by nature, but exist only in the context in which they were created.

Data Types

PHP provides types to indicate simple data storage.  String data indicates a sequence of characters that has meaning for the user, but not the program.  String data, as used above, is placed in quotes, either double or single. PHP recognizes numerical data so that it can make calculations, but uses no quotes to indicate the data.  Many other programming languages require the programmer to declare the a specific numerical type when a variable is declared, for example an integer is a whole number, and a float is a floating point or decimal number.  Languages that require data types to be declared in advance are called strongly typed.  Scripting languages like PHP and JavaScript are called loosely typed because they allow a variable to be loaded with numerical data without declaring a type.  View the following example:

$myNum = 1;
$myOtherNum = 3.2;
$myTotal = $myNum + $myOtherNum;
print "The total is: " . $myTotal;

We can do the math, and find the total should be 4.2.  However, what data types are involved?  Let's use a built in PHP function called gettype(), to determine what types of data the numbers reveal:

echo "myNum contains " . $myNum . " and it's type is " . gettype($myNum) . "<br />";
echo "myTotal contains " . $myTotal . " and it's type is " . gettype($myTotal) . "<br />";

When we view the output on a PHP page, we see that the two data types report integer and double, respectively.  When PHP saw a whole number, it treated it as an integer.  When a floating point number was added to it, the result was a decimal number called a double, which in PHP is the same as a float.  For more, see PHP Type Juggling 

Operators

Previously we saw a string of text we wanted to display and we connected (concatenated) it to the variable $myName with a 'dot' (period).  The period is a symbol of special significance to PHP, as the concatenation operator.  PHP has other operators like plus, minus, multiply and divide (+-*/) with which we can perform mathematical calulations.  An oddity of programming languages is the assignment operator, represented by the equals sign.  View the following example:

$myTotal = 1 + 2;

We traditionally think of an equals sign as comparing both sides of an equation. When we begin programming its good to remember to read each line of code approximately from right to left. In the above example we are assigning the values on the right side of the equals sign to the variable on the left. We can imagine that the value 3 is now stored in the variable named $myTotal.  Due to this effect we call the equal sign the assignment operator.

If we actually wanted to compare values we would use another operator, the comparison operator which in PHP is the double equal sign (==).  There is even a 'triple equals' sign, to indicate not only an identical value, but an identical data type (for example the number 3 and 3.000 may be an integer and a double).

Compound Operators

Besides ==,  PHP has other compound operators, where two operators placed together create a new operator.  View the following:

$myTotal = $myTotal + 1;

While the above looks odd, since we see $myTotal on both sides of the equal sign, remember that we are assigning a new value to what is on the left side of the equal sign.  Therefore, we are adding one to the original value and storing that value back to the same variable.  Here's the equivalent code with a compound operator:

$myTotal += 1;

The += operator allows us to get the same total, with less code.  Since we're adding one to the total, we can even take it one step further:

$myTotal++;

This special shortcut allows us to add one to any existing variable.  Here's another common example:

$myHTML .= "<b>Here's some more HTML for you!</b>";

In this example we're using the .= operator to concatenate (connect) more string data to an existing string inside a variable.  For more, here's a nice tutorial on PHP Operators

Variable Replacement

In PHP, values enclosed within single quotation marks will be treated literally, whereas those within double quotation marks will be interpreted. Placing variables in double quoted strings allows them to be interpreted.  As long as we're careful to leave spaces, we can place variable names directly into a double quoted string, and PHP will replace the variables, eliminating the need for concatenation:

$myNum = 1;
$myOtherNum = 3;
$myTotal = $myNum + $myOtherNum;
print "You added $myNum and $myOtherNum and the total is $myTotal";

PHP parses the strings in double quotes and replaces the variables, which it can see, because they start with a dollar sign, and have a space on either side.  If we want PHP to see more clearly where to replace a variable, we can add curly braces around the variables:

print "You added {$myNum} and {$myOtherNum} and the total is {$myTotal}";

PHP Functions

In PHP, as in most programming languages, many of the repetitive tasks we may need to perform have been addressed for us by the creators of the language.  PHP has many built in functions that perform string manipulations, formatting, increase security and make our jobs as programmers easier.  Here's an example of a useful function called date() which allows access to the system clock on the web server:

<i>MyWebsite, &copy; 2002 - <?php echo date('Y'); ?> </i>

In the above example we're only using the current 4 digit year from the system clock of the server.  We can get many variations on this idea by viewing the PHP.NET info on date().

We can also create our own user defined functions that include our code, plus existing PHP functions and other data.  Before we create our own functions, we should be sure there are no functions that do what we want to do already.  For an overview of built in PHP functions see the PHP Function Reference

Errors In PHP

When we work with PHP, as with any programming language, we can't expect to be perfect.  When we make mistakes in an HTML page, the browser generally will produce some sort of visible output.  In PHP we must be perfect, (or nearly so) because any mistake could create an error in a page, and crash our page.  PHP will rarely attempt to process the page any further, once a serious mistake has been encountered. 

If PHP has been configured to display errors, a page with a small typographical error could display something ugly like the following:

Parse error: parse error, unexpected $ in main.php on line 59

If PHP has not been configured to display errors, you could get an entirely blank page!  You can determine this is the case by viewing the HTML output.  If you see upper case HTML & BODY tags with no data, that is what is displayed by PHP when it has been configured to hide all errors.

We'll be working on Seattle Central's Zephir webserver, which has been setup to display errors.  Seattle Central's Edison webserver has been setup to hide PHP errors.  If we have a customer's commercial website, we'll call that a production server, and it may be appropriate to hide errors.  However, while we're building pages, we'll use a development server setup to show errors.  Frequently there is an interim server, called a testing server, which is designed for testing your code before it is deployed (sent) to the production server.

Source: Code vs Output

There is a danger working with server side programming regarding the visible source code of the HTML page. I try to make the distinction between output (the HTML presented to the browser) vs code (the combination of PHP/HTML that produces the page).  While in a straight HTML environment we can grab HTML output, make changes and re-upload a file.  In PHP you potentially have dynamic code, not a static page, and you may overwrite all your work!

PHP INI File

There is a single file in PHP called an initialization file, or php.ini file.  This file is used to establish environment settings for your specific installation of PHP.  It's possible to over-ride some of these settings inside individual files, or even write another php.ini file to overwrite the initially installed version.

We can view many of the settings inside our current PHP.INI file by using a special PHP command named phpInfo():

info.php View Code

The page produced displays information about the versions, settings and options set for the current installation of PHP. We view the data provided by phpinfo() to check configuration settings and for available environment variables on a given system.  For example we can see if error reporting has been turned off, which would result in no data being displayed, if PHP encounters an error.



We should never leave this phpInfo() data on an unprotected page on a client's system as it gives away important info that a hacker can use. 

Print this Page Back To Top

© 2000- 2010 newMANIC INC, All rights reserved