PHP for Designers

This is no longer available online but I found it on the Wayback Machine. It’s a post by Matt Mullenweg from March 31, 2004.


I first considered calling this “PHP for the aesthetically inclined,” but that sounded pretentious and I’ve always been fond of using the term “designer” in a more universal sense. I have a grand romantic notion of a “designer” being not just the person who insists you can’t use Comic Sans as the base font for the company Web page, but a consummate perfectionist who approaches every task with a careful eye for structure, form, and function.

Writing code is not very different from writing prose or poetry, it’s just a different medium and audience. There are rules of syntax, grammar, and style. In English, word choice can make or ruin a sentence. The PHP language is rich in strong and supple functions and choosing the right one is critical. In PHP you should strive for your code to be as simple as possible, but no more. It is a fine balance to maintain but will ultimately save you time and money.

I hope this introduction will demonstrate these principles and expand your understanding and application of PHP regardless of your previous skill.

Why PHP?

There is no “right” language for every single purpose. Like wrenches in a toolbox, different programming languages lend themselves to being particularly well-suited for specific uses, although each could be massaged into handling most tasks. Choosing the right language for the job is a decision I make on a daily basis. There are compelling reasons why I usually choose PHP over another server-side scripting language such as Perl or XSSI:

  • It’s easy to set up. In many hosting environments PHP is set up as a module, which is a technical way of saying that if you have a file with the .php extension it will generally execute PHP code without having to change file permissions or put it in a special directory like cgi-bin. This is not universally true, but it’s the common denominator for hosts that support PHP.
  • Embedding bits of PHP code inside primarily XHTML pages is easy.
  • PHP is portable. PHP can run under Apache or IIS or thttpd on Windows or Linux or BSD or… you get the idea. This increases the value of your code and also increases your hosting mobility.
  • PHP is popular. Surveys show it be the most popular Apache module ever, and Apache is the most widely used Web server.
  • PHP is cheap. Free, actually. PHP is open source software, which means a lot of things but most importantly means that PHP is a well-supported and stable platform that is available for low- or no-cost to anyone who wants to use it. You can run PHP (and Apache and MySQL) on your home computer or on thirty enterprise servers for the same price.

Those are the objective reasons. Subjectively I think that PHP is great for getting work done elegantly and fast, is easy to learn, and has a wealth of freely available code, scripts, and documentation.

Syntax

PHP code is always contained between the wrappers <?php and ?>. These indicate to the PHP engine that whatever is inside those starting and closing tags should be interpreted as PHP and nothing else. There are several alternate methods of indicating the same information to the PHP engine, but these are either non-standard or hinder compatibility, so for our purposes we will always use <?php ?>.

Comments: Say something

Comments are where you write things you don’t want executed. A single line comment may begin with two forward slashes, and nothing on the rest of that line will be interpreted by PHP. You can have multi-line comments by enclosing them between /* ... */, which some of you may recognize as the comment syntax in CSS. PHP comments are great because they aren’t output to the browser at all, which can be useful when you want to make a comment for future reference, for example:

<!-- Stupid hack for stupider IE 5.0 users -->

 

is more dangerous than

<?php /* Stupid hack for stupider IE 5.0 users */ ?>

 

In the second example the comment will never be seen by an end-user, even if he views the HTML source. The importance of commenting your work cannot be overstated. Things that may seem obvious to you today may be opaque a year from now when they need updating. Useful comments (not silly like the one above) can save you hours and usually only take seconds to write, if you write them as you go along. Don’t tell yourself you will go back and comment things later, because chances are you won’t.

Variables: Store it

Variables are places to store information. Variable names always start with a dollar sign and then have the variable name, which can have letters, numbers, or underscores but can’t start with a number. When naming variables it is best to use succinct names that are straightforward and communicate the variable’s content.

<?php
$weather = 'Bright and sunny.';
$age = 20;
$favorite_music = 'Jazz';
?>

You will find that your variable names may need to contain more than one word. There are two ways to do this: the first is called camelCase, where the first word is lowercase and subsequent words have their first letter capitalized; the second way is by using underscores to separate the words. Both are popular, and ultimately it comes down to personal preference. I prefer the underscore method because I find it easier to read with space separating words rather just a case hump. More important than which style you choose is sticking with it and giving descriptive yet short names to your variables.

Quoting and Escaping

In XHTML, attributes must be closed within quotation marks, which may be single or double quotes. This is useful because in PHP we assign strings to variables using quotes. If you use a quote of the same kind inside the string, then it must be escaped. For example:

$link = "<a href=\"http://example.com\">Example</a>";

As you can see we had to escape the quotes inside the string with backslashes. However taking what we know about quoting we can clean this up:

$link = "<a href='http://example.com'>Example</a>";

Although single and double quotes are interchangeable in XHTML, they aren’t in PHP. Double quotes tell the PHP engine to interpret any variables it finds in the string, and single quotes tell PHP to handle the string literally. For example:

<?php
$number_cds = 42;
echo "I have $number_cds CDs.";
?>

Output: I have 42 CDs.

<?php
$number_cds = 42;
echo 'I have $number_cds CDs.';
?>

Output: I have $number_cds CDs.

Using single quotes where possible results in nominally faster execution, but we’re talking fractions of milliseconds.

Functions

PHP has hundreds of built-in functions available for you to use. Functions take a number of arguments separated by commas and do something or return something. For example the date() function can take a string of characters and output a formatted string. To output the current year we could use:

<?php echo date('Y'); ?>

Output: 2004

How do I know that Y formats as 2004 (this year)? I looked it up quickly by typing in php.net/date which took me immediately to the reference page for the date() function. If there wasn’t a function named date, it would do a search and take me to the search results instead. This method of using the php.net Web site makes a great quick reference.

Ending Lines

We are going to finish our brief syntax overview exactly like you should end statements in PHP, with the semicolon. When you tell something to PHP, such as <?php $number_cds = 42; ?>, the semicolon tells it the statement is done.

Execution

Now it’s time to do something useful with what we’ve learned so far. How many HTML pages have you seen that have something like this at the bottom?

Copyright &copy; 2001-2003.

It’s pretty standard, but when it’s out of date it can look very unprofessional. Besides, after partying away New Year’s Eve, who wants to spend the next day updating the copyright dates on dozens of pages? We already know that we can echo out the current year using the date function, so lets update our example to use that and a proper en dash:

Copyright &copy; 2001–<?php echo date('Y'); ?>.

The PHP code was easily embedded, and now you never have to worry about updating that year again.

If all your pages have a .html extension and aren’t set up to parse PHP code and you don’t want to have to rename every file and update every link to use the .php extension, here’s a quick line you can put in your .htaccess file (assuming you use Apache and can have a .htaccess file) to have all .html and .htm files parsed by the PHP engine.

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

If you’re having trouble getting PHP to run at all, even in files with a .php extension, it’d be best to contact your host’s technical support.

So far we have barely scratched the surface of what is possible with PHP. I hope this has piqued your interest to explore other resources and watch for future PHP articles here at Digital Web.

matt_mullenweg.jpgMatt Mullenweg is a troublemaker who has an affinity for web technologies. He is the lead developer of WordPress, GPL blogging software and semantic personal publishing platform. He enjoys photography, writing, and playing the saxophone and piano.