PHP Scripting Language


Primary Author: Bob Pickle

What is PHP?

PHP is a popular scripting language that lets you do just about anything you want to do on a web site. It has much of the functionality of JavaScript, but runs on the server (server-side) rather than on the user's computer (client-side). Thus, there are no concerns about browser incompatibility with PHP like there is with JavaScript, and you don't have to worry about whether or not the user has JavaScript enabled on his computer.

One reason why PHP is so popular is that web hosting companies can use it for free, and it is also platform independent,


What can I do with PHP?


We'll cover some simple things below, but first, here is a list of more complex things we've done with PHP at Pickle Publishing, a site I manage:

1) A page that extracts, behind the scenes, the ASPseek search engine results offered by TAGnet, and that pastes those results into a page that looks like the rest of our site.

2) A complete shopping cart.

3) A content management system of sorts.

4) An expandable and collapsible menu system.

5) A spider that automatically updates the links on our "index" pages whenever we add new content to our site. These pages list some of our web pages, complete with descriptions, that fall into a particular category. The spider updates the titles, descriptions, and links, all automatically.

6) Our own search engine and page indexer.

7) A hit counter.

8) A method for running crontab jobs on a web host that doesn't allow users to run crontab jobs. (Crontab jobs are procedures that you want to run at specified times, like 4:00 am every day, or 2:00 pm each Monday, or 6:00 am on the first of every month.)

9) One function of that crontab job is to generate a free recipe newsletter every Monday and Thursday morning, and send it out to our mailing list.


One note of explanation on the newsletter: Research suggests that some email newsletters are only effective for a certain length of time. We therefore felt that if we cycled interests through about fifty newsletters, we would reach about as good a level of effectiveness as we could expect. We have all the components of the newsletters written in advance, and our PHP script assembles them and sends them out to our contacts, automatically repeating the series once it gets to the end. Regardless of when someone signs up, they get all the recipes. If you ever have tried to keep up an email newsletter, you'll realize the time-saving potential of such an approach.

And there's so much more one can do. For example, EllenGWhite.info features a poll on many pages, giving an opportunity for readers to respond. The poll software was entirely done in PHP, and was quite inexpensive.


How can I Learn PHP?

For starters, check out http://www.php.net/docs.php. On that page you'll find all sorts of links to documentation files in all sorts of languages and several formats. My favorite is the CHM version, which I keep on my Windows desktop. I regularly use its handy search feature to find the commands or explanations that I need.

Sample scripts abound on the net, some free and some not. I've found some helpful scripts at http://evilwalrus.com/ and http://www.hotscripts.com/PHP/. Take a look at some of what's out there, and you'll get an idea of both what you can do and how to do it.


What editor should I use?

There are different ones available. When we dove in, MS FrontPage couldn't handle PHP adequately, and so we looked elsewhere. The editor we finally settled upon was Webcoder from TSW. They have a free version available, and the paid version is quite reasonable. You can use it to do all your webmastering.

Whichever editor you settle upon, look for one that will color code your text so that you can visually tell the difference between comments, variables, constants, and functions, and regular HTML. The color coding will save you oodles of time.


How do I get PHP to work on my page?

Most web hosts have PHP enabled as an Apache module. We'll assume that's the case for you. It can also be invoked from a command line, or as a CGI program in your CGI bin.

If your web host provides you with PHP capability, all you have to do is put your script into a web page that ends with the extension ".php". When the web server sees that extension, it will send that page through the PHP parser before sending it out across the internet.

Alternately, if you want people to think that all your pages are straight HTML, you can add the following line to your .htaccess file. The cost to performance is extremely small:

AddType application/x-httpd-php .php .html .htm

Then even your files that end with ".htm" and ".html" will be checked for PHP code before being served to the user.

If your web host provides you with a control panel, you may be able to specify that HTML files be sent through the PHP parser without editing your .htaccess file.

Enclose all PHP coding within <?php and ?>, or, if allowable, <? and ?>. Don't forget to end every command with a semicolon.

One thing you'll learn quite quickly is that computer programming is very "legalistic," and PHP is no exception. While JavaScript allows you to fudge on some of those ending semicolons, PHP never does. It's great to have the spirit of the law, but if you don't have the letter too, you'll accomplish absolutely nothing when it comes to PHP


Okay, I want to start

A classic PHP example goes something like:

        echo "Hi. I'm a PHP script!";

Insert that on a page, upload it, and view it in your browser. If PHP is enabled and running on your web server, the above PHP coding will be totally gone from the HTML source that your browser receives, and all you'll find are the words, "Hi. I'm a PHP script!"

Or try the following:

        echo date("F j, Y, g:i a");

That will output the current date, formatted like "March 10, 2001, 5:16 pm." Don't like that format? There's so many possibilities to choose from that you'll never be able to try them all. See the PHP CHM manual under date() for full instructions.


Working With Forms

Let's modify the first example above just a little:

< ?php
             echo "Hi friend!";
             echo "Hi " . $_POST['firstname'] . "!";
? >

Okay, what does all that mean? Suppose you have a form on your page with a text input that carries the name "firstname." When the form is submitted, the server will hold the contents of that "firstname" field in a variable by the name of $_POST['firstname']. If that field was empty, or if the form has not yet been submitted, the above script will simply say, "Hi friend!" However, if "Tom" was in the "firstname" box, the above script will instead say, "Hi Tom!"

You've probably guessed that the periods in the above example are used to concatenate strings of characters. Want to skip a period or two and see if it works anyway? Try it, and you'll see again an illustration of why mankind should keep the Sabbath, if God's code is anything as precise as computer code is.

The above example only works for a form submitted using the POST method. If you use the GET method, you'll have to use $_GET['firstname'] instead. Or alternately, use $_REQUEST['firstname'], which works for both POST and GET for PHP 4.1.0 and above.

Suppose later you change the name of the page, or use the same form on another page. You'll have to change the action attribute of the form tag to the new page name. However, if you want to be more efficient, use the following:

< form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >

There are a number of $_SERVER variables. $_SERVER['PHP_SELF'] is the one that contains the name of the current page. Whatever the name of the page happens to be, will be the value of that variable. So if you use the above coding, the assigned action of the form will always be correct, regardless of the name of the page. That is, it will be correct if your form handler page happens to be the same page that contains the form.


How terms, variables, and constants work

Simplifying things a bit, we can summarize PHP by saying that it consists of predefined and user-defined functions, constants, and variables.

Examples of functions include date() and assign().

Any word that follows "$" is a variable. Variables can be assigned values multiple times by repeatedly specifying $this = "that". A variable might contain a single value, or it might be an array containing lots of values. In one of the above examples, $_POST was an array containing values for every field in the form. The one value we chose to use was the one from the "firstname" field, but there might also be a $_POST['lastname'] and a $_POST['address'].

If a variable is undefined, that won't cause any problem whatsoever. If "firstname" was undefined, missing entirely from our form, and we simply said,

echo  "Hi " . $_POST['firstname'] .  "!";

our page would say, "Hi !"

Constants are a bit different. They can only be assigned values once, and they are assigned values by using the following sort of expression:

assign("firstname" , "Frank") ;

If a constant is undefined, the PHP parser will treat it as a string. If it is defined, then the parser will substitute the value that was assigned to that constant. For example, "firstname" in $_POST['firstname'] is automatically considered a string since it is surrounded by quotes. If we take the quotes away, the PHP parser will first check to see if "firstname" is a constant that has been assigned a value. If it has been assigned the value of "Frank," then $_POST[firstname] becomes the same as $_POST['Frank']. If it has not been assigned any value at all, then $_POST['firstname'] and $_POST[firstname] end up being exactly the same thing.

If you insert a variable into a string of text that is enclosed in double quotes, like "Hi $name!", then that string will end up displaying that variable's value, if it has a value. This is only true for double quotes, not single quotes.

Want to use some of these special characters in a string? Use the escape character, the slash, as in the following:

$ text =  'He said, "I\'m going to town with $dollars." ';
$ text =  "He said, \"I'm going to town with \$dollars.\"" ;

In the first example, if the single quote isn't escaped, then that legalistic PHP parser will think your string began with "He" and ended with "I." Your script will come to an abrupt halt, and you'll be looking for what you did wrong.

In the second example, the double quotes have to be escaped instead of the single quote, for the same reason as above. Without escaping the double quotes, the PHP parser will think that the string has ended before it has. Additionally, the dollar sign has to be escaped if you don't want the parser to think that $dollars is a variable.

There might be rare occasions in which you want a variable's name to change depending on the circumstances in your script. If you enclose $which in braces and prefix it by "$", then when $which = "red", the PHP parser will interpret ${$which}as $red. If $which = "blue", then ${$which}will be $blue.

And that's as complicated as we want to get right here.


Time Savings?

Can PHP help reduce the time it takes to maintain my web site?

Absolutely. Suppose that every web page on your entire site contained the following lines at the top and bottom:

< ?php include "includes/header_footer/header_default.php"; ? >
< ?php include "includes/header_footer/footer_default.php"; ? >

Whenever you want to change the look of your site, just change those two files, and your entire site will change automatically.

In other words, put all the code from each and every page that is the same into those two files.

Of course, we all know that the top HTML coding of each page is not the same. For one thing, the title tag is different. That's no problem. In that header_default.php file, just put the following:

< title ><?php echo $title; ?>< /title >

Then, at the top of each page, before the include statement that includes your header file, assign a value to $title:

$ title = "Explore the beauties of God's Word !" ;

Now the title of your page, as it appears in your browser, will be "Explore the beauties of God's Word!"

The top and bottom of pages tend to be the same, but there are a few differences. Assigns those differences to variables, and use those variables in these header and footer template pages, and you have saved yourself a whole lot of work when it comes to site management.

Some software packages out there can do this kind of thing for you without you knowing what is going on, but you may appreciate the added flexibility and control you can have by doing it in this way.



How can I automate the maintenance process for the links to my various pages?

The navigation used for the main menus at Halos.com, another site we manage, is just the thing to explain one way to do it. Each page on that site includes via PHP a header file that utilizes a variable we'll call $menu. That variable is assigned a value in the main page before the header file is included. The value of that variable is the name of a single file which contains two main parts:

  1. an array containing each menu item of the menu and its associated link, and
  2. coding that takes the array and turns it into a working menu.

Additional variables on each page that affect the menu we'll call $which and $expand. If a menu item matches one of the values in the array $which, then the appearance of that item (like color or underlining) is changed so that the reader will know that he is in that category or on that page.

If the menu happens to be expandable, then whatever items match the values found in the array $expand will be expanded, while the others will not be. EllenGWhite.info uses this approach quite a bit to expand certain items for certain pages, and other items for other pages.

When I would rearrange pages using MS FrontPage, I had to wait a long time on a large site for FrontPage to update all the links. With today's faster computers it wouldn't take as long, but the speed of the above PHP approach cannot be improved upon. Change a single file containing all the items for a particular menu, and all the pages using that menu instantly change.

Another advantage over FrontPage is that this method doesn't add lots of HTML comments that increase the size of the file being served, and download time.

Want to put an entire book online? Check out Creation's Tiny Mystery. Surf from chapter to chapter, and watch the navigation change at the top and bottom of each page. The coding involved uses some of the above techniques. Check out the radiohalo catalog and the yet-unfinished appendix, where the appearance of the navigation changes to accommodate the material. Even though some of the documents in the appendix require three levels of navigation, everything for all the pages is contained in a single file. Since chapter one, the book could be online. As more parts get uploaded, adding but a few entries in that single file updates the links on  every affected page automatically. Imagine having to update 100+ web pages manually!


Path Names

What's an easy way to keep my path names straight, regardless of where my pages are located?

Suppose you have a file named start.php in a directory called /includes/. You could then say at the top of each page:

< ?php

include $_SERVER['DOCUMENT_ROOT'] . "/includes/start.php";

? >

$_SERVER['DOCUMENT_ROOT'] is a variable that contains the file path of the root directory of your web site. Regardless of what directory the current page is in, the PHP parser will be able to find start.php, because you have stated its location in terms that are absolute. Then, in start.php you could have the following line:

< ?php

assign("TEMPLATE_PATH" = $_SERVER['DOCUMENT_ROOT'] . "/includes/templates/");

? >

Now on each page that you want to include "my_template.php," simply put:

< ?php

include TEMPLATE_PATH . "my_template.php";

? >

The constant "TEMPLATE_PATH" will supply the correct path automatically, and the PHP parser will be able to find and include your template file. The advantage of doing it this way? If you ever change the location of your template files, you'll only need to change one line in one file in order to update your entire web site.


Enjoy the wonderful world of PHP!

(c) 2024 Adventist Webservant Assistance - Webmaster & Website Help, Tools and Resources.