TweetFollow Us on Twitter

Getting Started with PHP

Volume Number: 20 (2004)
Issue Number: 11
Column Tag: Programming

Getting Started with PHP

by Dave Mark

Qne of the things I love most about writing this column is the opportunity to play with different technologies. I especially love it when this means playing with a technology that takes a sharp left turn from the traditional. A perfect example of this is PHP, a programming language that looks like C, smells like C, but takes C in a very different direction.

What Makes PHP Different

In most programming languages, the output from your program goes to the user, in some form or another. For example, in your Cocoa program, you might put up a window, then display some data in the window, perhaps with a scrollbar that lets the user scroll through the data and buttons that allows the user to accept the data or cancel whatever process brought up the data in the first place. The point is, some portion of your program is directly dedicated to interacting with the user.

PHP is different. Though PHP does sport a set of user interface functions, one of its strongest uses is as a means to dynamically generate web content. For example, suppose you were building a web site and you wanted to serve up one set of pages for folks running Safari and a different set of pages for other folks. There are lots of ways to do this, and PHP offers its own mechanism for doing this (and we'll take a look at this a bit later in the column).

More importantly, suppose you wanted to build a web site that was data-driven. For example, you might build a table that lists the most up-to-date statistics from your weekly Halo 2 league. You could embed the statistics directly in your HTML, or you could use PHP to build an interface to an open source database like mySQL or PostgreSQL. You'd write one PHP-laden web tool for entering the data, then another for displaying the data.

PHP is idea for managing HTML forms. Especially if you'll want to back your forms up to a database. Once you get a taste of PHP, you'll definitely want to play with it yourself. And the cool thing is, if you know a bit of C, you'll find PHP quite easy to pick up.

Installing PHP

In the golden, olden days of Mac OS X, installing PHP was a bit of an adventure. For starters, you downloaded the latest version of Apple's developer tools, then used Google or the like to find the most recent source code distribution of PHP that some kind soul had ported to Project Builder (later Xcode) format. Each source code distribution came with a set of scripts that would drive the process of compiling the source and installing the binaries in the right place. These scripts are known in the Unix world as makefiles. Once you downloaded the distribution that was right for your version of Mac OS X, you ran the makefile, got yourself a sandwich and, hopefully, by your last bite you had yourself an installed version of PHP. More often than not, however, you ran into a funky error that required you to tweak some permission or other, or perhaps rename a directory. Bottom line, this was not rocket science, but it was far from trivial.

Nowadays, PHP has really hit the mainstream. Soon after each rev of PHP or Mac OS X release, web pages pop up with instructions on the best way to install that version of PHP on your particular configuration of Mac OS X. Some folks even go to the trouble of creating traditional Mac OS X installers that do all the hard work for you.

I used Google to search for:

"php 5" "mac os x" 

Why php 5? When I wrote this article, PHP 5.0.2 was the latest release. By the time you read this, I suspect PHP 5.0.3 will be out, if not an even later version. But the major release will still likely be 5, so a search for PHP 5 will work.

The site I chose for this month's column has a packaged installer for PHP 5.0.1, as well as a forum section where you can message with other folks with similar experiences. Hopefully, by the time you read this, the installer will have been updated to the latest version, but for the purposes of this discussion, 5.0.1 will do just fine.

Here's the link to the main page:

http://www.entropy.ch/software/macosx/php/

Note that this install is for the version of PHP designed to work with the Apache web server that ships with Mac OS X. You are going to install PHP on your own machine, then put our php test pages in the Sites folder in your home directory. In effect, the Apache web server on your local machine will be serving up pages to you, without going over the net. This is a great way to learn PHP. With this setup, you can make changes to your code without using an FTP client. Just edit the file in place, save, then test. As long as you save your change, you don't even need to close the file before switching back to your browser to hit the reload button to retest the page. This is an extremely efficient way to work.

If this is still a bit confusing to you, not to worry. After we do the install, we'll run a few examples so you get the hang of working with PHP.

Figure 1 shows the install instructions from our download page. You'll want to click on the link labeled PHP 5.0.1 for Apache 1.3 (remember, the page might have been updated to a more recent version of PHP). Click the link and a disk image will be downloaded. It's about 20 megs, so it might take a while. Once the .dmg file downloads, the disk image will mount. Navigate into it and double click on the file named php-5.0.1.pkg (or whatever the .pkg file is called when you download it).


Figure 1 - Installation instructions for installing PHP

Follow the installation instructions and PHP should install without a hitch. To verify that the install went OK, fire up Terminal and enter these two commands:

ls -F /usr/local 
ls -F /usr/uocal/php5/ 

For you non-Unix folks, the ls command lists the contents of the specified directory or file. The -F option asks ls to put a * at the end of executable files and a / at the end of directories. This makes an ls listing a bit easier to understand.

Figure 2 shows my results after I did my PHP install. Note that PHP is installed in the directory /usr/local/php5/.


Figure 2 - A Terminal listing showing the location of the newly installed PHP files

To test the installation, create a plain text file using a tool like TextEdit, BBEdit, or Xcode. Be sure that your text files are plain text files. Personally, I use BBEdit for all my PHP and web editing. Here's a link to a page that will let you download a demo of BBEdit:

http://www.barebones.com/products/bbedit/ demo.shtml

Regardless of how you create the plain text file, here's what goes in it:

<?php phpinfo() ?> 

Save this line in a file named test.php and place the file inside the Sites directory in your home directory. It is critical that the file have the .php file extension so the Apache web server knows to pass the file through the PHP pre-processor before serving up the page. The PHP pre-processor will scan the file looking for PHP code to interpret. PHP code always starts with "<?php" and ends with "?>". You can have more than one block of PHP code in a single file. We'll show examples of this a bit further along in the article.

The line above contains a single PHP statement, a call of the function phpinfo(). This function returns a bunch of information about your PHP installation, all formatted in a two column HTML table. Why does the function return HTML? That's one of the most important aspects of PHP. Your PHP code will generate HTML code, which will appear in line with the HTML code in which it is embedded. Once the PHP code is done running and its output is incorporated into the surrounding HTML, the full HTML is returned by the server and rendered by your browser. Again, we'll get into this more later on in the article.

For the moment, save your one line php file into the Sites directory in your home folder. To test the file, use this link:

http://127.0.0.1/~davemark/test.php

Obviously, you'll replace "davemark" with your own user name. The 127.0.0.1 is an IP address that represents your local machine. The ~davemark represents the Sites directory of the user davemark. And, of course, the file name test.php is the file we are passing along to the Apache web server.

Figure 3 shows the output when I ran test.php on my machine. Obviously, this is just the first few lines of a very long series of tables.


Figure 3 - The output from phpinfo().

Hello, World!

Our next example shows what happens when we mix PHP and HTML. Create a new plain text file and type in this code:

<html>
	<head>
		<title>PHP Test</title>
	</head>
	<body>
		<p>This is some pure HTML loveliness.</p>
		<?php
			echo "<p>Hello, World!</p>";
		?>
		<p>Did we echo properly?</p>
		<?php
			echo date("r");
		?>
		<p>It works!!!</p>
	</body>
</html>
</PRE>

Save the file as hello.php and save it in your Sites directory. When you send this file to Apache, Apache will note the .php file extension and send the file to the PHP pre-processor. The pre-processor will scan the file, copying the HTML to its output as is, until it encounters the open PHP tag:

<?php 

As soon as it hits the end of those characters, the pre-processor starts interpreting the rest of the file as PHP code, until it hits the close PHP tag:

?> 

Once it hits that close tag, the processor runs the PHP code it just scanned and places the output from the PHP code following the HTML code it just copied. In the hello.php example, this means executing this statement:

echo "<p>Hello, World!</p>"; 

and copying the output from that statement into the HTML stream. The echo command simply copies its parameters to output, where it joins the HTML stream.

Once the close PHP tag is encountered, the pre-processor continues copying the HTML to its output until it hits the end of the code or encounters another open PHP tag.

Note that our example has two chunks of PHP code. The second chunk executes this line of code:

echo date("r");

The first version of echo you saw copied the text string to output. This version of echo has a function as a parameter. In that case, the PHP pre-processor calls the function and returns the output of the function call as input to echo. echo simply echoes that output to the HTML stream.

Confused? Type in this link to execute your copy of hello.php. Be sure to replace my user name with your user name:

http://127.0.0.1/~davemark/hello.php

The output of this example is shown in Figure 4.


Figure 4 - hello.php in action.

To get a true sense of this process, choose View Source from Safari's View menu. This will show you the merged PHP output and HTML code. Here's my merged source:

<html>
	<head>
		<title>PHP Test</title>
	</head>
	>body>
		<p>This is some pure HTML loveliness.</p>
		<p>Hello, World!</p>		<p>Did we echo properly?</p>
		Fri,  1 Oct 2004 11:01:48 -0400		<p>It works!!!</p>
	</body>
</html>

Notice that the output from the PHP commands is right there in the mix. One bit of funkiness, though. Notice that the PHP generated HTML did not include a carriage return, so the follow-on HTML starts on the same line as the end of the PHP output. In this line of output:

		<p>Hello, World!</p>		
		<p>Did we echo properly?</p>

you can see that the two paragraphs are on the same line of source. This will not affect the final output, but it does make the source a bit harder to read. An easy solution to this is to embed a carriage return character "\n" at the end of each line of PHP output.

Here's a new version of hello.php:

<html>
	<head>
		<title&lgt;PHP Test</title>
	</head>
	<body>
		<p>This is some pure HTML loveliness.</p>
		<?php
			echo "<p>Hello, World!</p>\n";
		?>
		<p>Did we echo properly?</p>
		<?php
			echo date("r");
			echo "\n";
		?>
		<p>It works!!!</p>
	</body>
</html>

Note that we added the "\n" directly at the end of the first echo's parameter string. Since the second echo did not use a string, we added a second line of code, just to echo the "\n".

When you run this chunk of code, the output will be the same. But let's take a look at the source code that is generated when you do a View Source:

<html>
	<head>
		<title>PHP Test</title>
	</head>
	<body>
		<p>This is some pure HTML loveliness.>/p>
		<p>Hello, World!</p>
		<p>Did we echo properly?</p>
		Fri,  1 Oct 2004 11:39:16 -0400
		<p>It works!!!</p>
	</body>
</html>

Notice that the carriage returns we added made the intermediate source a bit easier to read.

Include Other PHP Files

Here's another example, for you folks who like the organizational power of include files. This one is a slight mod of one from the php.net site. Create a new file named vars.php and type in the following code:

<?php
	$color = 'green';
	$fruit = 'apple';
?>

Save the file in the Sites folder and create a second new file named inc_test.php. Here's the code:

<html>
	<head>
		<title>PHP Include Test</title>
	</head>
	<body>
		<?php
			echo "<p>A $color $fruit</p>"; // A
			include 'vars.php';

			 echo "<p>A $color $fruit</p>"; // A green apple
		?> 
	</body>
</html>

Save this file in the Sites folder as well. Run this example by typing in:

http://127.0.0.1/~davemark/inc_test.php

Remember to replace davemark with your username. Your output should look like this:

A

A green apple

In a nutshell, inc_test.php is made up of two identical echo statements, with an include statement in between. The echo statements print the value of two variables, each of which is set in the include file. Notice that the first echo does not have values for $color and $fruit and does not print anything for those values. The second echo occurs after the include file. Since the include file sets the values for the variables, the second echo prints those values.

This example was included as a bit of food for thought. Many web sites achieve their unified look and feel through included header, nav bar, and footer files, as well as through a judicious use of variables. No doubt you'll want to take advantage of include files and variables as you build your own PHP projects.

Restarting Apache

If you happened to reboot your machine since you did the PHP install, you may have noticed that Apache is no longer running. Not to worry. There are two easy ways to restart the server. The simplest way is to select System Preferences... from the apple menu, then select the Sharing icon. On the Sharing page, click on the Services tab and make sure the Personal Web Sharing checkbox is checked. As soon as you check the checkbox, Apache will be started and the Start button will change to Stop so you can stop the server. Unless Apache runs into a problem at restart, it should be restarted automatically when you restart your machine.

Another way to start and stop the server is by using the apachectl command in Terminal. Start up Terminal and type in this command:

sudo apachectl restart

You'll be prompted for your admin password, since the sudo command executes a shell with root privileges. Type in the password and the Apache server will be stopped (if it is running) and restarted. Either way works just fine.

Till Next Month...

We'll be doing a bit more with PHP next month. In the meantime, check out the web site http://www.php.net, the official web site for PHP developers. There are a ton of resources on this site, including complete on-line and downloadable PHP documentation. To figure out why the date() function did what it did, find the search field at the top right of the main page and type in the word "date", make sure the popup menu says "function list", then hit return or click on the right arrow icon. This will take you to the "date" documentation.

Check out all the format character options in Table 1 and play with a few of them. Enjoy, and I'll see you next month.

Oh, if you haven't done so already, be sure to head over to http://spiderworks.com and sign up. The new version of Learn C


Dave Mark is a long-time Mac developer and author and has written a number of books on Macintosh development. Dave has been writing for MacTech since its birth! Be sure to check out Dave's latest and greatest at http://www.spiderworks.com.

 
AAPL
$117.60
Apple Inc.
-1.03
MSFT
$47.47
Microsoft Corpora
-0.12
GOOG
$541.08
Google Inc.
+1.81

MacTech Search:
Community Search:

Software Updates via MacUpdate

MacUpdate Desktop 6.0.3 - Discover and i...
MacUpdate Desktop 6 brings seamless 1-click installs and version updates to your Mac. With a free MacUpdate account and MacUpdate Desktop 6, Mac users can now install almost any Mac app on macupdate.... Read more
SteerMouse 4.2.2 - Powerful third-party...
SteerMouse is an advanced driver for USB and Bluetooth mice. It also supports Apple Mighty Mouse very well. SteerMouse can assign various functions to buttons that Apple's software does not allow,... Read more
iMazing 1.1 - Complete iOS device manage...
iMazing (was DiskAid) is the ultimate iOS device manager with capabilities far beyond what iTunes offers. With iMazing and your iOS device (iPhone, iPad, or iPod), you can: Copy music to and from... Read more
PopChar X 7.0 - Floating window shows av...
PopChar X helps you get the most out of your font collection. With its crystal-clear interface, PopChar X provides a frustration-free way to access any font's special characters. Expanded... Read more
Carbon Copy Cloner 4.0.3 - Easy-to-use b...
Carbon Copy Cloner backups are better than ordinary backups. Suppose the unthinkable happens while you're under deadline to finish a project: your Mac is unresponsive and all you hear is an ominous,... Read more
ForeverSave 2.1.3 - Universal auto-save...
ForeverSave auto-saves all documents you're working on while simultaneously doing backup versioning in the background. Lost data can be quickly restored at any time. Losing data, caused by... Read more
Voila 3.8.1 - Capture, annotate, organiz...
Voila is a screen-capture, recording, and annotation tool that is a full-featured replacement for Mac's screen-capture and screen-recording capabilities. It has a large and robust set of editing,... Read more
SyncTwoFolders 2.0.6 - Syncs two user-sp...
SyncTwoFolders simply synchronizes two folders. It supports synchronization across mounted network drives and it is a possibility to run a simulation showing in a log what will be done. Please visit... Read more
Duplicate Annihilator 5.1.1 - Find and d...
Duplicate Annihilator takes on the time-consuming task of comparing the images in your iPhoto library using effective algorithms to make sure that no duplicate escapes. Duplicate Annihilator detects... Read more
HandBrake 0.10.0 - Versatile video encod...
HandBrake is a tool for converting video from nearly any format to a selection of modern, widely supported codecs. Supported Sources: VIDEO_TS folder, DVD image or real DVD (unencrypted -- CSS is... Read more

Latest Forum Discussions

See All

Screeny (Utilities)
Screeny 1.0 Device: iOS iPhone Category: Utilities Price: $.99, Version: 1.0 (iTunes) Description: Screeny is an utility app that helps you save space consumed by screenshots. It screens your camera roll and helps you to filter and... | Read more »
Tilt to Live Bundle Set to Arrive This T...
Tilt to Live Bundle Set to Arrive This Thanksgiving Posted by Ellis Spice on November 25th, 2014 [ permalink ] One Man Left has unveiled an upcoming Tilt to Live bundle, allowing players to get the series for a di | Read more »
BattleLore: Command (Entertainment)
BattleLore: Command 1.0 Device: iOS Universal Category: Entertainment Price: $9.99, Version: 1.0 (iTunes) Description: ***NOTE: Compatible with iPad 2/iPad mini, iPod touch 5 and up and iPhone 4S and up – WILL NOT RUN ON EARLIER... | Read more »
Weather Or Not Review
Weather Or Not Review By Jennifer Allen on November 25th, 2014 Our Rating: :: STYLISH WEATHER REPORTINGiPhone App - Designed for the iPhone, compatible with the iPad Check the weather quickly and conveniently with Weather or Not... | Read more »
The All-New Football Manager Handheld 20...
The All-New Football Manager Handheld 2015 is Available Now Posted by Jessica Fisher on November 25th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Six iOS Games to Get You Ready for Thank...
Image Source: Friends Wiki At this point in the month, you or at least a few people you know are probably getting ready to scramble around (or are already scrambling around) for Thanksgiving Dinner. It’s a hectic day of precise oven utilization, but... | Read more »
Call of Duty: Heroes: Tips, Tricks, and...
Hello Heroes: What’d we think of Call of Duty‘s take on Clash of Clans? Check out our Call of Duty: Heroes review to find out! Just downloaded Call of Duty: Heroes and need some handy tips and tricks on how to get ahead of the rest? As we often do,... | Read more »
Call of Duty: Heroes Review
Call of Duty: Heroes Review By Jennifer Allen on November 25th, 2014 Our Rating: :: CLASH OF FRANCHISESUniversal App - Designed for iPhone and iPad Mix Clash of Clans with Call of Duty, and this is what you get.   | Read more »
Slider Review
Slider Review By Jordan Minor on November 25th, 2014 Our Rating: :: SLIDE TO PLAYUniversal App - Designed for iPhone and iPad Slider has all the excitement of unlocking your phone screen.   | Read more »
oh my giraffe (Games)
oh my giraffe 1.0.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0.0 (iTunes) Description: Eat fruits while being chased by lions. Cut the vines to send fruit plummeting onto the lions. Don't worry, your flexible... | Read more »

Price Scanner via MacPrices.net

Early Black Friday MacBook Pro sale: 15-inch...
 Best Buy has posted early Black Friday prices on 15″ Retina MacBook Pros, with models on sale for $300 off MSRP on their online store for a limited time. Choose free local store pickup (if available... Read more
A9 Chips Already?
It’s barely more than a couple of months since Apple got the first A8 systems-on-chip into consumer hands, but rumor and news focus is already turning to the next-generation A9 SoC. Apple Daily... Read more
NewerTech Announces NuGuard KXs Impact X-Orbi...
NewerTech has announced updates to its family of Impact X-Orbing Screen Armor bringing military grade, triple layer protection to Apple’s new iPhone 6 and 6 Plus. Like all models in the NuGuard KXs... Read more
13-inch 1.4GHz MacBook Air on sale for $889,...
 B&H Photo has the 13″ 1.4GHz/128GB MacBook Air on sale for $889 including free shipping plus NY tax only. Their price is $110 off MSRP. B&H will also include free copies of Parallels Desktop... Read more
Save up to $300 on Macs and iPads with your A...
Purchase a new Mac or iPad at The Apple Store for Education and take up to $300 off MSRP. All teachers, students, and staff of any educational institution qualify for the discount. Shipping is free,... Read more
Apple refurbished Mac Pros available for up t...
The Apple Store is offering Apple Certified Refurbished Mac Pros for up to $600 off the cost of new models. An Apple one-year warranty is included with each Mac Pro, and shipping is free. The... Read more
Jumptuit Launches One-Tap Windows 8.1 iTunes...
Jumptuit has launched Windows 8.1 support for One-Tap iTunes Sync. with which Windows 8.1 users can now easily sync their iTunes libraries with Microsoft OneDrive. Jumptuit provides easy access from... Read more
Apple restocks refurbished 13-inch 2014 Retin...
The Apple Store has restocked Apple Certified Refurbished 2014 13″ 2.6GHz Retina MacBook Pros for up to $230 off the cost of new models. An Apple one-year warranty is included with each model, and... Read more
CEA Study Finds More People Recycling Electro...
A new study by the Consumer Electronics Association (CEA) finds that electronics recycling receives the continued and growing support of consumers. According to the CEA,s Recycling and Reuse Study,... Read more
15″ 2.2GHz Retina MacBook Pro on sale for $17...
 B&H Photo has the 2014 15″ 2.2GHz Retina MacBook Pro on sale today for $1749. Shipping is free, and B&H charges NY sales tax only. B&H will also include free copies of Parallels Desktop... Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
*Apple* Solutions Consultant (ASC)- Retail S...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
Project Manager, *Apple* Financial Services...
**Job Summary** Apple Financial Services (AFS) offers consumers, businesses and educational institutions ways to finance Apple purchases. We work with national and Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.