TweetFollow Us on Twitter

Enabling the Embedded: PHP

Volume Number: 19 (2003)
Issue Number: 11
Column Tag: Programming

UNTANGLING THE WEB

Enabling the Embedded: PHP

by Kevin Hemenway

We've covered CGI scripts, but how is PHP any better?

In the past five months, we've turned on our built-in Apache web server, fiddled with the quick and dirty Server Side Includes (SSI), configured CGI to run scripts written in languages like Perl, Python, and Ruby (see also Jim Menard's article on Ruby, MacTech, March 2003) and, in general, found that this high-falutin' web serving stuff ain't all that difficult. However, we've yet to launch into a peaceful meandering of PHP, one of the easiest and more popular programming languages available for web development.

In the first of assuredly many self-congratulatory, pointless, and cliched "personal milestone" articles, our amazing, exciting, over-the-top, and action packed sixth entry will... will... welp, it'll teach you about configuring and customizing PHP with your Apache web server. Quick, over there! Bearded lady! Vegas pole dancer! Scarily painted clown!

But First, The Who... Oh, Look! Historical References!

As most developers know, it's hard to talk about a language without getting into religious wars ("my recursively-named is better than your yet-another!"), personal dislikes ("whitespace?! I can't believe Python considers it syntax!"), and programming theory ("procedural is to OOP as 'that's odd' is to 'eureka'!"). Regardless, there is one clear advantage to using PHP under Apache: "forking" (or rather, the lack thereof).

See, anytime a CGI script is requested, Apache forks (or spawns) a new process to handle this request, and then executes the code within this newly created environment. This happens pretty quickly and without fuss or muss, but with one downside: every time a process is spawned, the interpreter (be it Perl, Python, Ruby, etc.) has to be reloaded into memory--nothing is remembered or cached from previous runs. The more and more times this happens (due to heavy incoming traffic, for example), the slower the web server will get: Apache will spend more time waiting for processes to finish than actually serving their results.

This doesn't happen with Apache's Server Side Includes. Since SSIs are built into the web server via a default module called mod_includes, everything is handled internally and no forking is required. This same approach is used with the mod_php module: by preloading PHP into each and every Apache process, you remove the need for the forking and interpreter loading overhead. The only downside is slightly larger memory, a trade-off worth taking.

Let's see how mod_php is configured within Apache.

Enabling The PHP Module Within Apache

As you'll see, configuring PHP under Apache is very similar to what we've seen in our previous articles--this stuff should be old hat to you by now. As we've been doing from the start, to find out more about a feature, we'll search for the keyword within the httpd.conf file. Our first matches for "PHP" are our familiar LoadModule and AddModule lines:

LoadModule php4_module        libexec/httpd/libphp4.so
AddModule mod_php4.c

Similar to our previous articles, these two uncommented lines (i.e., not prefaced with a # character) load the module located at /usr/libexec/httpd/libphp4.so into our Apache web server. You may notice that the module name doesn't match what we've grown to expect (mod_includes for Server Side Includes, mod_cgi for CGI scripts, etc.), as it's called libphp4.so instead. There's nothing special about this... everyone calls it mod_php regardless of what the actual file representation is.

Our next "PHP" search research should also look familiar:

#
# To use PHP files:
#
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps

Similar to Server Side Includes, these two lines tell files ending with a php or phps extension to become associated with the PHP module. You'll notice there's no AddHandler equivalent like with SSI or CGI; largely, that's because the "application" of the MIME-type instructs mod_php to become their "handler". It's sort of like Adobe Acrobat Reader handling .pdf files (which have a MIME-type of application/pdf). If you've already designed your entire site around .html files and don't feel like revamping your structure or redirecting old URLs, you can modify the first line like so:

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

This will enable support for PHP code in both .php and .html files. Be careful not to go nuts with this: you don't want to add file extensions "just because". Whether you actually use PHP code within an .html file or not, mod_php will process it like you did, and that can unnecessarily slow down your server when your traffic starts getting heavier.

With that, we've run out of search results in our httpd.conf--PHP has already been configured for our use. But how do we know for sure, besides attempting to run some PHP code and introducing varying levels of user error? To find out which third-party modules are loaded into your web server, check Apache's error_log where, for every startup, the "server tokens" will be logged. These tokens reflect the server version number, what operating system it's running on, and information on which third-party modules have been loaded.

Since we've been searching for "PHP" throughout the httpd.conf, let's do the same with our error_log. Figure 1 shows the results of a grep PHP /var/log/httpd/error_log shell command, listing the server tokens each restart of our Apache server logged. grep is a great tool for quickly searching a file from the command line.


Figure 1: Grepping our error_log for Apache's server tokens.

Now that we know PHP is enabled, let's learn more by writing our first script.

Far More phpinfo() Then You've Ever Wanted

Since PHP has been enabled for any file that ends with .php, we're going to create a test.php file within our personal user directory (/Library/username/Sites/). The contents of this file will be simply:

<? phpinfo(); ?>

Any PHP code you write will need to be sandwiched within a starting and ending delimiter, <? and ?> in this example. You may also see and use starting delimiters like <?php (often recommended for greater portability over the shorter <?), and <?= (which can be used to quickly echo a variable or expression). With our delimiters in place, we'll use one of PHP's built-in functions, phpinfo(), to spit out gobs of information about our installation. Figure 2 shows partial output of http://127.0.0.1/~username/test.php:


Figure 2: The first page of phpinfo()'s many.

Obviously, there's a lot of stuff here, and a good portion of it won't be immediately (or even ever) useful, but there are a number of interesting things to discover. I'll touch briefly on a few of the more helpful entries below, but you can always find out more by searching through the online documentation at http://www.php.net/.

  • The first section we come across gives us the version number of PHP (which we previously saw in the output of our error_log), the time the module was built, and more importantly, the configuration line used to build it. This becomes helpful if we ever build our own version of the module, adding a new feature or tweaking an existing one. Also helpful is the configuration file path, which tells us where the php.ini file lives (or should live). The .ini file is similar to Apache's httpd.conf and allows us to tweak the runtime settings of the module.

  • Next up is a long list of configuration directives. asp_tags, off by default, allows you to use <% and %> as your delimiters, whereas short_open_tag controls whether you can use the <? we've already encountered. display_errors should ultimately be turned off when we're ready to use PHP on a production system, and any errors configured with error_reporting should be sent to an error_log instead (though we'll use log_errors to send them to our Apache error_log -- confused yet?). Whether incoming data will automatically be escaped for database use is magic_quotes_gpc's intent; since it's on by default, we'll have to be careful to stripslashes if we use the data elsewhere. Finally, register_globals will ensure that visitors or users can't easily pollute your namespace with GET or POST parameters, though some programs (most notably, the excellent osCommerce, http://www.oscommerce.com/) require it to be turned off.

With PHP certifiably enabled, let's configure it to log errors into our Apache error_log. Knowing about errors is always a very good thing, and by enabling all of them, we'll be able to write better scripts (similar to the Perl equivalents strict and warnings; see last column). To do this, we'll have to modify the php.ini file which lives in /usr/lib/.

Tweaking PHP's Initialization

There's one problem with editing this file: it doesn't exist. Since PHP is currently configured with all the standard and expected defaults, Apple never shipped a dummy php.ini file for us to modify. This isn't cataclysmic... most of the settings we care about can be modified in the relevant PHP file itself. Take, for example, the following two scripts:

script example #1:
<?php humiliation; ?>

script example #2:
<?php error_reporting(E_ALL); humiliation; ?>

They're combined output can be seen in Figure 3. As is obvious, there's an error in the code, but only when reporting is enabled would we actually be informed--meanwhile our script would trudge on regardless, perhaps getting deeper and deeper into a well of cascading problems. Further error configuration is possible by using the ini_set function to set relevant values, but who wants to worry about doing that for every .php file?


Figure 3: Our PHP script, with and without error reporting.

Our first task, then, is to create a /usr/lib/php.ini file. Thankfully, we don't have to build one from scratch, as the latest and greatest default version is available from CVS: http://cvs.php.net/co.php/php-src/php.ini-disthttp://cvs.php.net/co.php/php-src/php.ini-dist. If you're new to PHP or security-conscious (rightfully so), it may be better to blindly trust the more secure version, available from http://cvs.php.net/co.php/php-src/php.ini-recommended. Both are heavily commented and should be read fully to understand their ramifications.

For our purposes, we're going to use the php.ini-recommended file. It's always best to start with the most secured installation you can, then slowly open it up when you know what you're doing. The side effect of using this version is, happily enough, logging exactly how we want: none to the browser, everything to the error_log. Save the php.ini-recommended file to your Desktop, open a Terminal, and type the following:

cd Desktop
sudo cp php.ini-recommended /usr/lib/php.ini
sudo apachectl restart

Since /usr/lib/ is a protected directory, you'll need temporary super-user privileges to copy the new configuration into place. That's where sudo comes in. Likewise, since we're making a change to PHP, which is loaded as part of the Apache web server, we'll need to restart Apache with apachectl, which also assumes super-user privileges. Any time you make a change to httpd.conf or your new php.ini file, you'll need to restart Apache before the changes will take effect.

You can ensure your configuration changes are enabled by checking the output of phpinfo, as well as running the first of our script examples. The browser output will remain unchanged, but the error will be logged into Apache's error_log--see Figure 4.


Figure 4: With our new php.ini file, errors are logged to Apache's error_log.

With our new php.ini file working correctly, you'll want to keep in mind that register_globals is off (and you may have to turn it on for some applications to work properly), magic_quotes_gpc has been disabled, so that you'll need to addslashes if you plan on putting content into a database, and that included files and libraries can only exist in the current directory (although you can add more lookups via include_path, which previously had include /usr/lib/php).

Homework Malignments

In our next column, we'll take a look into databases, specifically the MySQL server, and how to integrate our PHP scripts with them. Because it's so easy to use PHP to hook into any database, you'll often be hard-pressed to find a script or application that doesn't require the existence of one. Also, with Panther available by the time you read this, we'll cover any relevant differences in your web serving capabilities. For now, students may contact the teacher at morbus@disobey.com.

  • I missed an opportunity to say "stick a fork in it; it's done".

  • If you're looking to pick up a book on developing sites with PHP, check out PHP and MySQL Web Development by Luke Welling and Laura Thomson. The Second Edition is available from Sams Publishing and covers programming in PHP, fiddling with your first database and SQL statements, and then combining the two together to create a number of different applications to learn practical techniques from.

  • You may have noticed that the PHP shipped with OS X is only 4.1.2, even though, at time of writing, 4.3.3 is available. If you absolutely must be using the latest version, be sure to check our Marc Liyanage's downloadable package available from http://www.entropy.ch/software/macosx/php/. It's full of features not enabled in Apple's version (compare http://www.entropy.ch/software/macosx/php/test.php to ours), and is easily removable for when you want to take a step back to the defaults.


Kevin Hemenway, coauthor of Mac OS X Hacks and Spidering Hacks, is better known as Morbus Iff, the creator of disobey.com, which bills itself as "content for the discontented." Publisher and developer of more home cooking than you could ever imagine (like the popular open-sourced aggregator AmphetaDesk, the best-kept gaming secret Gamegrene.com, the ever ignorable Nonsense Network, etc.), he's trying desperately to find time to work on his next book outline. Soon, he says, soon. Contact him at morbus@disobey.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »

Price Scanner via MacPrices.net

Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more
Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more

Jobs Board

Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
IT Systems Engineer ( *Apple* Platforms) - S...
IT Systems Engineer ( Apple Platforms) at SpaceX Hawthorne, CA SpaceX was founded under the belief that a future where humanity is out exploring the stars is Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.