Coding - What is PHP? How do I use it?

This tutorial was written for users.f2s and first published there.

Resources

Introduction

When I arrived at F2S, I had little experience in web designing. I soon heard of server-side includes (SSI) and was burning to try them out.

To my dismay, I found out that F2S did not support SSI. Anwers to my protests were of the form "use PHP instead! it can do everything SSI does, and much more!".

I didn't know what PHP was, and a trip to the official PHP site gave me the impression the monster was too ferocious for me to tackle. I was wrong. But once you know PHP, the basics are so simple that nobody ever bothers to explain them, which can make PHP seem inaccessible to the non-initiated. This article will hopefully fill in that blank.

If you know nothing about PHP and are wondering what all the fuss is about, or if you want to know how to use PHP to replace SSI, you will find the anwers here. But you won't find anything about CGI scripting with PHP or advanced programming. For that, look at our PHP links page.

Short description of PHP

PHP is server-side:
Your browser doesn't realise the pages it is viewing are initially written with PHP. All it receives is an HTML page - as complex or as simple as you want.

PHP is HTML-embedded:
A PHP page can be simply an HTML page with a little PHP sprinkled here and there (we'll see how).
The PHP bits are parsed ("translated") by the server - in the examples presented here, they will be mainly used to produce more HTML code. The HTML code on the page is sent directly to the browser.

PHP has similarities with other programming languages:
C and Perl are two of them. In my case, learning a bit of Perl really helped me get started and understand what PHP could do for me - and how it worked.

Inserting PHP code in HTML

To insert bits of PHP code in an HTML page, all you have to do is insert it in a special tag, like this:

<?php any amount of PHP code ?>

Note: depending on your HTML editor, or if you are using XML, you might need to use one of these alternate "PHP tags":
<? "blah blah blah" ?>
<% "blah blah blah" %>

Inserting an xml declaration

If your server supports short opening tags (<? ... ?>) and you want to include an xml declaration at the beginning of your document, you will run into trouble. You might want an xml declaration if you decide to validate your document as xhtml (which would be a good thing, between you and me).

The solution is to insert this line of code just before the DTD:

<?php print("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n"); ?>

If you don't know what a DTD is, do start validating your code.

Here is an example which uses a variable:

<?php print("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
  <title> <?php print($pagetitle); ?> </title>
</head>
<body>
HTML code... <?php PHP code ?> ...HTML code... <?php PHP code ?> ...HTML code... etc...
</body>
</html>

The print statement in the "title" line simply sends the value of the variable $pagetitle to the browser. We use the same principle to produce the xml declaration at the beginning of the document—except that instead of asking php to print a variable, we give it a string of text instead.

Let's say we had previously assigned a value to $pagetitle, by using the following expression (somewhere in the beginning of the same page, for example):

<?php $pagetitle='This is my page!'; ?>

Then what the browser would receive is:

<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
  <title>This is my page!</title>
</head>
etc...

As you can see, as far as the browser is concerned, this is just HTML...

Here is another example, using an include:

<?php print("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
  <title>This is my page!</title>
</head>
< body>
HTML code... <? require("nav.inc"); ?> ...HTML code... <? PHP code ?> ...HTML code... etc...
</body>
</html>

The require expression tells the server to stick in the contents of the file named "nav.inc", instead of the PHP tag. Let's say this file contains the main navigation table for your site and looks like this:

this is the beginning of the file

<div class="nav">

  <a href="/" title="Home page">Home</a><br />
  <a href="/computers/" title="Everything about computers">Computers</a><br />
  ...
  <a href="/recipes/" title="My favorite recipes">Recipes</a><br />
</div>

the file ends here

This is what the server sends to the browser:

<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
  <title>This is my page!</title>
</head>
<head>
HTML code...

<div class="nav">

  <a href="/" title="Home page">Home</a><br />
  <a href="/computers/" title="Everything about computers">Computers</A><br />
  ...
  <a href="/recipes/" title="My favorite recipes">Recipes</a><br />
</div>

...more HTML code... <? PHP code ?> ...HTML code... etc... </BODY>

Again, the browser has no idea that PHP exists.

Comments on the HTML code for the navigation div:

A little PHP syntax

Here is a little information about what matters and what doesn't when writing PHP.

PHP.net is your friend!

PHP.net can be overwhelming for the beginner. I spent hours getting lost in that site before I found out how to use it efficiently. Though the interface seems to be a little more friendly than it used to be, here are a few tips which might come in handy:

More about variables, print and echo

Variables can have just about any size. For example, all the text you are reading now could be the value of one big variable.

Variable names start with a dollar sign ("$"), followed by an alphabetic character or an underscore, optionally followed by alphanumeric characters or underscores.
They are case-sensitive. They do not have to be declared or assigned a type.
PHP also supports array variables (e.g. $somevar[3] = "something";) and objects, but their discussion is beyond the scope of this article.

Print and echo do just about the same thing: they send their argument to the browser. There is a small difference between them, but I'm not yet sure what it is... ; )

When using print, echo, or when assigning a string value to a variable, you have the choice between using double quotes or single quotes (if the argument is a naked variable, you can also use no quotes at all).
Single quotes will reproduce the text between them with no modifications. Line breaks, spacings, variable names and fun characters will all come out how you printed them. But! if the text between the quotes contains single quotes, you have to replace them by the escape sequence "backslash-quote": "\'". And what if you want a backslash? Use a double backslash: "\\". That's all.
Double quotes will replace variables by their value, and ignore newlines and tabs. Here are some escape sequences: newline = "\n", tab = "\t", double quote = "\"", backslash = "\\", dollar = "\$"...
Until you know better, I recommend using single quotes unless the string contains a variable to be replaced.

If you want to define a very long variable (for example, lots of text), you might want to use the here doc syntax.

An empty variable, e.g. $potato = ''; will return false when its boolean value is called for. It will not create an error if you attempt to print it.

More about includes

As it should be clear from the example above, an include is a simple ASCII file, and there is no special "dressing" to put around it. Just cut out a chunk of HTML or php from a page and stick it in a separate file: you have an include.

Include files can have any extension. You can name an include "blahblah.bla" if you wish.
It is common to name them "something.inc", but using other extensions can sometimes make sense. For example, a file with a ".txt" extension will be viewable directly in most browsers, whereas trying to view includes with other extensions may simply result in the browser prompting you to "save as...". Naming includes is a perfectly personal choice.

The require function replaces itself with the contents of the file it calls, whereas include is more like a branch that points to it. This can make a difference if you are using a loop to call different includes: if you use require, the statement will be replaced by the first file during the first loop, and you will end up with (e.g.) three times the same file instead of three different files. If you are not quite sure which to choose, follow this rule of thumb: In control statements and functions, use include. Otherwise, use require (which is supposed to be a little faster).

An include can call another include. The include is read just as a normal PHP file, which means that you can put in an include anything that you would put in a "normal" PHP file.

Calling an include with relative or server-relative urls sometimes creates trouble. I usually use include($_SERVER['DOCUMENT_ROOT'] . "/path/filename"); or include("http://".$_SERVER['HTTP_HOST'] . "/path/filename") - do a few tests on your own server to see what works for you. You will get a listing of server variables like $_SERVER['DOCUMENT_ROOT'] . "/code> or $PHP_SELF with the function phpinfo(): upload a simple php file containing the line <php phpinfo(); ?>, and view it.

Making a template

Here is a method I have used to create quite simply a general design for a site. I have included it here as an example of how you can quickly get PHP to work for you. Of course, this is only the beginning of PHP...
PHP4 offers a built-in template feature, but I honestly haven't figured it out...

I used to create a unique page with a "skeleton" of the design I wanted for my site, i.e. all the HTML that is constant from one page to another. The parts that change from page to page were replaced in it by variables. This page was then "required" at the end of another page which gives values to these variables.

I have now reverted to using top and bottom includes, which does not require putting the whole content of a page into a big variable (I liked the idea at the start, but it turned out to be a real pain). Here are the steps to take to do something similar.

  1. Make a standard page for your site. Don't forget to polish up your HTML and validate it ; ) ...
    Once you have done that, separate the code which comes before the content (the top include) from that which comes after it (the bottom include
  2. Identify the "variable" parts of your page. The bits of HTML that change from page to page will be replaced by PHP variables, like in the "title" example higher up in this page.
  3. Create a new file, which could be named here "example.php", and give the necessary values to the needed variables to produce the finished page once the server has parsed the PHP. Here is what this "PHP page" looks like.
  4. You can now create as many "PHP pages" as your site requires, which all call up the design template. This allows you to create new pages without worrying about design and layout, and it also allows you to change the design completely by modifying a single file.
    If you keep entering the same value for a given variable, it might make sense to include its value directly in the "design template"...

If you have questions or suggestions about this "template method" or anything else in this tutorial, feel free to email me: tara@climbtothestars.org.

Using XML and PHP for a weblog

This might sound complicated. It is indeed not exactly "basic", but that shouldn't scare you off. I am now using this system for my weblog and for other pages which are constructed as a collection of posts, and it is in fact pretty straightforward.

First and foremost, do not let the word "XML" intimidate you. If you don't want to start writing your own DTD to validate it, you'll find that it is not more difficult than writing HTML. It is simply a way of organizing information and marking up its structure with tags, like this:

<post id="573021" lang="en" class="thought"> <date>Thursday, August 03, 2000</date> <time>17:34</time> <slug>Secret</slug> <body> <p>Your words will not give your secret away.<br /> Your silence will.</p> <p>A secret leaks through what you leave unsaid.</p> </body> </post>

The way I have chosen to organize the information in this post is strictly personal— you may do as you please, as long as it is coherent, and the basic XML syntax (which is the same as (X)HTML) is observed.

The idea is to store information (the posts) in a format similar to this one. It has the advantage of being completely independant of any layout one may wish to present it with, and in a format which will not be outdated before a very long time. In addition to that, we will discover that this technique gives us some of the functions one could expect of a database (for example, showing on the page only the posts in French or in English), without going through the hassle of actually setting up and maintaining the database.

Here is the basic principle:

Take a look at what the finished script could look like. The comments should guide you through it for the moment—please let me know if you would like more precise explanations, I'll be very happy to give them!

© 2000 by users.f2s and Tara Star

This site will look much more pretty in a browser which supports web standards, but it is accessible to any browser or Internet device. Browsers which do not support CSS will get this message, even if they are otherwise standards-compliant. Do you want to upgrade?

French - français! Ce site aura l'air bien plus joli dans un navigateur conforme aux standards du web, mais il est accessible avec n'importe quel navigateur ou dispositif Internet. Désirez-vous faire une mise à jour?