Introduction


What exactly is PHP?

PHP stands for "PHP: Hypertext Processor".  Its a pretty popular scripting language, almost always used for web applications.  It has a vaguely C/C++ like syntax, is very loose on data types, and has rudimentary object-orientation abilities.  Its power lies in its flexibility of syntax, easiness to learn, and its massive library of built-in specialized functions.  You can do things ranging from using aspell to working directly with zlib compression, all as part of the language.  Some consider this bloat, but PHP remains fast and stable.



Ok, that was way over my head.  What exactly would I use PHP for?

You would probably use it for a web application.  This is usually the role that cgi fills, and the concept of what is happening is very similar.  Basically, when someone hits a url on your site with an extension configured to be handled by PHP, such as .php, Apache has PHP execute the code inside that file.  The code inside is your program, and that is where you store your logic.  So you do your thing, maybe its inserting someone's name into a database for a guestbook on a website.  You can do almost whatever you want behind the scenes, including sending custom http headers back to the browser and sending dynamically generated html to the browser, such as the contents of the guestbook.

 

Not all tasks are suited to PHP or server side processing in general.  Many newbies make the mistake of trying to use PHP to do something that something like JavaScript in the client's browser would be responsible for, such as responding to certain mouse movements.



Where can I get PHP?

The website for PHP is http://www.php.net.  You can select from among multiple releases, including win32 binaries, and find alot of good documentation.



The Language


Enough Q&A, no we will see how PHP is used.


First off, you start your PHP script as you would any other HTML file.  Just create a plain text file on your web server, but give it the extension `.php`.  Inside this file, you are free to insert any combination of PHP and HTML that you want.  When Apache's PHP module parses the file, it will execute any code found within html-style PHP tags.


Valid PHP tags are:

  <?php echo "PHP code here"; ?>

  <? echo "PHP code here"; ?>

  <script language=php>

   echo "PHP code here";

  </script>

  <% echo "PHP code here"; %>


Personally, I use the second style.  There's actually some real PHP code in there, using the echo keyword.  Echo is pretty much the same as print in other languages, or echo in shell scripting.  Whatever you put after the echo keyword will get sent to the web browser.


I don't really have the time or space to go over the actual tenets of programming, but I will present the syntax basics for PHP.


There are three main control structures: selection, sequence, and repetition.  Also there is object orientation, which sits sort of above the former three.  PHP handles all of these perfectly well, with the exception of its object syntax feeling a bit hackish. 



Selection

Selection is typically in the form of `if-then-else` and `switch` statements:


  if ($variable == 1)

   echo "The variable is 1";


The above is a simple if statement.  If $variable is 1, then it will echo "The variable is 1" to the client browser.  There are a couple things to be seen here.  First is that the condition is in parenthesis.  All selection and repetition statements put the condition being tested in parenthesis, similar to C/C++.  The second thing to note is the name $variable.  In PHP, variables are always prefixed with a $.  Otherwise, PHP will treat it as a keyword or function, and if it is neither, then it will throw a syntax error.  The data type of $variable doesn't matter because PHP is a loosely typed language.  In the above case, it might be a string, char, integer, or something else.  We don't know, and PHP doesn't care.




The third thing to note is the use of a double-equal sign in the comparison in the if statement.  This is another C-ism: if you are testing equality, you use a double-equal sign.  A single equal sign is always assignment.  Had I used a single equal, like so:


  if ($variable = 1)


then the test would always be true, because it would simply perform an assignment, which should always succeed.  Success, or being said to be "yes" is the same as being true.  So, you can put functions in your condition tests, and if they return true, then the "then" part will trigger.  This is very useful, especially when using repetition, as I will demonstrate later.


The fourth thing to note is the tab I put in front of the echo.  This isn't necessary, but when I right code, I indent when I move into different contexts of execution just for the sake of organization.  Like C, C++, and other languages, PHP is very liberal about whitespace.  If I was a masochist, I could have written it as follows:


  if ($variable == 1) echo "The variable is 1";


When you have pages upon pages worth of code, condensed into a few lines, it gets a little hard to follow.  The final thing to note is that a semicolon is used to mark the end of an instruction.  In the above case,  the semicolon terminates my echo statement.  If I wanted, I could do:


  echo "The variable is 1";  echo "The variable is still 1";


and things would work fine.  Because of PHP's liberal whitespace rules, I could put tabs or carriage returns or whatever I wanted between one instruction and the next.


We can do more complex if statements than what we've seen.  Multiple lines, and multiple cases are possible, and are generally done as follows:


  if ($variable == 1) {

   echo "The variable is 1";

   echo "\n";

  }

  elseif ($variable == 2) {

   echo "The variable is 2";

   echo "\n";

  }

  elseif ($variable == 3) {

   echo "The variable is 3";

   echo "\n";

  }

  else {

   echo "The variable is neither 1 nor 2 nor 3";

   echo "\n";

  }


Above, we see a block if statement, multiple elseif statements, and an else statement to wrap it up.  I'm enclosing the statements in curly braces because if an `if` or associated statement has more than 1 line, they must be enclosed in a code block, which is accomplished by the curly braces.  The "\n" that I echo in each one is a newline character.  There are a few other special characters like this that can be looked up on the web.  The elseif statements will try to catch what slips through the beginning if statement, and the else statement is a catch all for whatever slips through the preceding elseifs.  Both statements are optional.


 Alternatively, the above snippet of code could be written as a switch statement, as follows:


  switch ($variable) {

   case "1":

    echo "The variable is 1";

    echo "\n";

    break;

   case "2":

    echo "The variable is 2";

    echo "\n";

    break;

   case "3":

    echo "The variable is 3";

    echo "\n";

    break;

   default:

    echo "The variable is neither 1 nor 2 nor 3";

    echo "\n";

    break;

  }


A switch statement basically checks the value of the variable you tell it to, $variable in this case, and if it matches a case we give it, then it will execute that case.  The `break` is present to break us out of the switch statement, and return to normal execution.  The default case is optional and acts as a catch all, analogous to an else statement.



Repetition

Repetition is usually used when you don't know ahead of time how many times you may want to perform something, so you can perform it a variable amount of times.  It is very useful for processing repetitive data, such as perhaps the records out of a guestbook for a web page.


The most commonly used form of a control loop is a while statement.  It will test a specified condition, and if true, will execute the instructions we enclose.  When it is done executing our instructions, it will test the condition again, and if true, execute our instructions again, and so on.  Once our condition becomes false, the loop stops, and execution resumes after our loop.  For example:


  $number = 0;

  while ($number < 10) {

   $number++;

  }

  echo "Loop is complete.";

The above loop will test $number to see if it is less than 10, and if so, it will perform our instructions.  You will notice that we set $number to 0 just before entering our loop, so our loop should execute 10 times.  We only have 1 instruction inside our loop, and that is to increment $number; to add 1 to it, in other words.  This is accomplished by the use of the increment operator, ++.  Once we fall out of our loop, execution will resume at the first line after our loop, which will echo that the loop is complete.


The loop could have been rephrased as a for loop as follows:


  for ($number = 0; $number < 10; $number++) {

   //there is nothing to be done here

  }

  echo "Loop is complete.";


The syntax of the for loop doesn't offer anything over the while loop in functionality, its just structured differently.  Some tasks are more syntactically pleasing when presented in a for loop, but in the end, it comes down to the preference of the programmer.


Let's take a closer look at the syntax of the for loop.  It starts with the for keyword, followed by what we would expect to be a condition in parenthesis.  This time, however, we have more than *just* a condition to be tested; we actually have three things to tell PHP to do, separated by semicolons.  The first thing is we tell PHP is a one shot thing we want to do before we start the loop.  In this case, it is to set $number = 0.  This is analogous to when we previously set $number = 0 outside our while loop.  The second thing is the condition we want to test.  Simple enough to understand.  The last thing is what we want to do at the tail end of our loop, each time we execute.  In this case, it is to increment $number.  Because that was the body of our previous loop was to increment $number, we don't need to put anything in the actual body of our loop.


Just for kicks, I left a comment inside of the body of our for loop.  PHP uses C/C++ style comments.  Double slashes are used to comment a single line, and block comments are to be enclosed in /* and */ like so:


  /* This

  is

  a

  block

  comment */



Sequence Control

"Sequence Control" is sort of a misleading name because selection and repetition are also forms of sequence control.  So, in this section, I will discuss functions.


A function is a predefined set of instructions, essentially a custom keyword.  Functions can do all sorts of things, and they pave the way to object oriented programming.  Almost all of the specialized abilities that have been added to PHP are presented in the form of functions.  Defining a function of our own is simple enough:


  function PrintMyLug() {

   echo "Cvale " . "-" . " Central Valley Area Linux Enthusiasts";

  }


If I put the above into my PHP script, then I've essentially created a keyword named PrintMyLug, and when we use that keyword, PHP will execute the echo statement we placed inside.  You might be wondering what that lone period is.  That is PHP's append operator, it simply appends what is on its right and left.  You might also be wondering what that empty set of parenthesis is for.  That is where we put our parameter list, which is a definition of what arguments we can accept when someone uses our function.  Consider the following:


  function PrintSomething($something) {

   echo $something;

  }


Putting $something in the parenthesis tells PHP that we want the first argument given to our function to be presented to the function body as $something.  So, we could call our function like this:

 

  PrintSomething("Cvale - Central Valley Linux Enthusiasts");


and PHP would echo the argument we gave to it.  Its possible to take as many arguments as we want, all we have to do is separate them with commas.  The parameter list of our function is a one to one mapping of the arguments that it can be called with to variables that we want to access in our function body.


Another valuable ability of functions, besides code organization, is returning a value.  If we have our function return a value, we can use it in assignment operations.  Consider this snippet of code:


  Add2Numbers($number1, $number2) {

   return $number1 + $number2;

  }


Because the above function has a return value, we can use it in an assignment operation:

  $Sum = Add2Numbers(5, 10);


$Sum will be holding the number 15.  You can return just about anything you like in a function, but one of the more versatile things to return is a true or false.  If we return a true or false, then it is a trivial matter to use our function as a test condition in a control loop or an if statement.  This is a great method for some sort of repetitive operation: you store the operation logic in a function, and make it return true if it succeeds, and false if it fails or is done, then have a while loop just call your function as its test condition.  The loop will keep running until you return a false to it.


Many of PHPs built in functions do this, the method outlined above is particularly useful for dealing with databases, such as MySQL.  I will demonstrate this in a moment, but first, a little background.


A database table is logically a two dimensional table composed of records as rows, and fields as columns.  A single row would be an individual item in the table, and each column would be a different piece of data.  For example, imagine a row from a table of user information.  Columns in this table would be things like your first name, last name, username, password, etc.  So, typically, when you work with a database, you look at a record, or row, and then examine the individual columns, or fields.  This is how one typically access a database in PHP.


Now to the demonstration.  Imagine we have this user table, and we only want to print the first name, last name, and username from each record.  We would accomplish this by iterating through each record with a repetition loop, and address the individual tables we want as we would arrays, because an array is what PHP actually presents to use.  I'm going to have to use just a drop of SQL code to show this to you, but just saying the SQL in out loud in english should be enough to understand it.


  $sql_result = mysql_query("select fname, lname, uname from user_table");

  while ($record_row = mysql_fetch_array($sql_result)) {

   echo "First name: " . $record_row["fname"] . "\n";

   echo "Last name: " . $record_row["lname"] . "\n";

   echo "Username: " . $record_row["uname"] . "\n";

   echo "\n\n";

  }


The above code starts off by executing a SQL query and storing the result into $sql_result.  The test condition is actually a variable assignment.  Basically, it has PHP fetch the "next" row in $sql_result as an array, and to store that row into the array $record_now.  The actual body of our while loop is simply the process of pulling fields out of the array and printing them, with some newlines sprinkled in for formatting.  The loop will continue to iterate until mysql_fetch_array() returns a false, which will happen when it runs out of rows.  Also, both times we do a variable assignment above, it doesn't matter what type of data our variable was before, PHP forces it to become a different type appropriate for what we are storing into them.  This is commonly referred to as casting.



Conclusion

Even though this presentation seemed pretty long, it was only scratching the surface.  There is still alot more to be explained, particularly the way PHP handles objects.  What has been presented, though, should be enough to get an intermediate programmer started doing practical things in PHP.  As previously mentioned, almost all of the extensions for PHP to do specialized things are presented as functions, so its a very simple process to step forward and use them.