OS X web development server

1

Category : Apache, PHP, Server configuration

I think Mac based PHP developers most commonly install an application like MAMP to handle the perceived hard work when it comes to setting up their working environment. OS X does come preinstalled with most of what you need to develop PHP websites though and it’s pretty easy to get up and running. Why install extra 3rd party software, taking up space and system resources, when Apple has done it already?

This guide starts with a clean installation of Mac OS X 10.6.4 (Snow Leopard) and walks through the steps of setting up your dev server. It finishes with a run through of an application called VirtualHostX which is by no means necessary but I think it helps give a smooth development experience.

Start with Apache

Obviously Apache is the cornerstone to the whole idea so it seems like a logical place to start this guide.

OS X uses Apache for it’s built-in web sharing feature so enabling it couldn’t be easier. Go to “System Preferences > Sharing” then turn on “Web Sharing”.


You’ll be given an IP address that others can use to access your server but of course you can do so by visiting http://localhost/ from your own machine. Try that now and you’ll be greeted by Apache’s familiar, if underwhelming, default page.


Apache’s default location (where’s you’ll find the page shown above) is /Library/WebServer/Documents and to get to your own Sites folder you’ll need to open http://localhost/~[username]/. If you’re the only person using your Mac and you’d find it more convenient if http://localhost/ went directly to your own Sites folder, you can make a simple change to Apache. Run the following command in the system terminal:

sudo pico /etc/apache2/httpd.conf

Then find the DocumentRoot directive and change it to your Sites directory, i.e. DocumentRoot “/Users/[username]/Sites”. Note that throughout this guide I am assuming you store your websites your account’s “Sites” directory, if that’s not the case simply amend any paths you see.

Now restart the server (by disabling then re-enabling web sharing in the prefs pane) and refresh the localhost page. You should be greeted with your own home page now.

Enabling PHP support

Just like Apache, PHP is included with OS X although it’s not enabled by default. To get it working edit the httpd.conf file by running this line in the system terminal:

sudo pico /etc/apache2/httpd.conf

Find the line “LoadModule php5_module libexec/apache2/libphp5.so” and uncomment it then save the file and exit the editor.

Make a PHP configuration file by  running this in the system terminal:

sudo cp /etc/php.ini.default /etc/php.ini
sudo pico /etc/php.ini

You should configure PHP for your own preferences but if you’re not familiar with the php.ini file just get yourself up and running by finding the directive “short_open_tag” and changing it’s value to “On”, and then uncomment the directive ”date.timezone” and give it a suitable timezone – for me that would be “Europe/London” but there’s a full list at http://php.net/date.timezone. As this is a development server you may also want to turn on “display_errors” to aid debugging. Save the file and exit the editor once you’re done editing.

Now restart the server again using the sharing prefs pane.

To test PHP make a new file in your Sites folder called info.php and include the following code:

<?php
phpinfo();
?>

Open that file in your web browser and you will get an overview of PHP’s capabilities. If not double-check that the correct line has been uncommented in httpd.conf and that you have restarted Apache since enabling PHP.

All good so far! Now let’s add database support.

Installing MySQL

OS X doesn’t come with MySQL so it’s the one component you’ll need to install for yourself. Fortunately MySQL has an easy install process so run along to http://www.mysql.com/downloads/mysql/ and download the DMG archive for your system.

You’ll find that they give you the main MySQL server, a prefs pane item and a startup item. I’d recommend install all three of these components. The following image shows their prefs pane.


By default MySQL won’t set a top-level password but that’s something you’ll want to do for increased security. On a development machine it may not seem necessary but it’s good practice so after everything’s installed run the following at the system terminal:

/usr/local/mysql/bin/mysqladmin -u root password [newpassword]

For some reason the installer doesn’t create a my.cnf configuration file either, which you’ll need if you ever want to customise the installation.

sudo cp /usr/local/mysql/support-files/my-large.cnf /etc/my.cnf

You might like to restrict the installation a little more but I’ll leave that admin up to you. This guide is really just about getting everything working.

By now MySQL is fully functional but PHP isn’t aware of it so we need to update a few lines in the php.ini configuration file. Using the system terminal:

sudo pico /etc/php.ini

Now uncomment the directives “extension=php_mysql.dll” and “extension=php_mysqli.dll” and amend the predefined MySQL socket paths to “mysql.default_socket = /tmp/mysql.sock” and “mysqli.default_socket = /tmp/mysql.sock“.

Restart the server again (using the sharing prefs pane) and if you refresh your info.php page you should see that MySQL has been enabled.

You’ve now got a fully functional Apache + PHP + MySQL development server on your Mac and all you’ve had to install is MySQL. You can stop here if that’s all you wanted to achieve but I’m going to carry on and introduce VirtualHostX to try and make life a little easier.

Using VirtualHostX

What VirtualHostX essentially does is automatically configure your system’s hosts file and Apache’s vhost file so that you can access your development websites using a simple url rather than localhost followed by one (or often more) nested directories.

VirtualHostX only costs about £16.50 ($25 at the time of writing) and the convenience it delivers makes that money well spent. You can run the trial version if you’re unsure whether or not you need it.

http://clickontyler.com/virtualhostx/

So, download and install VirtualHostX now. When you run it for the first time it brings up the setup wizard.


The wizard will first create a backup of the operating system’s default Apache configuration, so you can always roll back if something breaks, and then it makes a minor change that tells Apache you want it to run virtual hosts. This is a perfectly safe change and is the way Apache would normally be run.

Before we go on to setup a vhost you need to have a target website on your computer. This can be any website, located anywhere on your Mac, but I like to keep all my websites within my Sites directory and for this demo I’m going to make SQL Buddy accessible from the convenient domain “dbadmin”.

Download SQL Buddy from the above link, extract it to a new folder called “sqlbuddy” within your Sites directory, and add your MySQL root password (defined earlier) to the SQL Buddy config.php script. With that the website will be accessible at the address http://localhost/~[username]/sqlbuddy/ but that’s a bit messy so open VirtualHostX and add a new host as per the following image.


Press “Apply Changes” once done and then you’ll able to quickly access your database administration by going to http://dbadmin/ – that’s tidier isn’t it?


I generally use VirtualHostX to setup development website’s using the real domain but prefixing it with “dev” rather than “www” so I don’t have to remember directory paths from my web root, or handle them within the website’s scripts.

That’s it!

I’ve probably made this guide a little more wordy than necessary but hopefully you’ll see that setting up a development server in OS X 10.6 is really simple – really just a case of installing the MySQL package and editing two system files.

It’s worth pointing out that, with all the latest OS X updates at the time of writing this guide, the built-in Apache is version 2.2.14 and it is preconfigured with the popular rewrite module. PHP is version 5.3.1 and it supports the most commonly used modules plus “pear” is also supported from the system terminal.

SXSW 2010 visual records

Category : Design, SXSW

I actually missed out on all but one of the keynotes at SXSW this year (because there always seemed to be something else I should be doing at the same time) but the organisers put these graphical records on display outside of the main exhibit hall and they caught my eye.

Click the individual images to see a larger version.

Opening Remarks with Danah Boyd

Saturday, 13th March 2010


by Heather Willem (imagethink.net)


by Ty Wallis (theillustratedidea.com)

Sunday Keynote with Valerie Casey

Sunday, 14th March 2010


by Sunni Brown (sunnibrown.com)


by Varick Rosete (varickrosete.com)

Keynote Interview with Evan Williams and Umair Haque

Monday, 15th March 2010


by Sunni Brown (sunnibrown.com)


by Karen Ingram (kareningram.com)

Keynote Interview with Daniel Ek and Eliot Van Buskirk

Tuesday, 16th March 2010


by Janie Underhill (idea-360.com)


by Stacy Weitzner (boldmusecreative.com)

Beyond web-safe fonts with Typekit

Category : CSS, Design

Custom fonts are a hot topic in the web design world at the moment because we’ve finally reached the point where all major browsers support their use via standard CSS. Now we can link to fonts of our choosing rather than relying on what is likely to be installed on the user’s computer.

You would expect the easiest, and maybe the best, way to get started with custom fonts is to find the typeface you want and then use CSS code similar to this:

@font-face {
  font-family: MyFont;
  src: url(http://www.mysite.com/MyFont.ttf);
}

p {
  font-family: MyFont, serif;
}

There are three big drawbacks to this method though; (i) you must be really sure that you’re licensed to use the font on the web, (ii) the font file must be in format that’s supported by the user’s browser, and (iii) the font file will almost certainly be a very large by web standards. All of these concerns can be addressed with Typekit.

What is Typekit?

Typekit uses JavaScript to inject the necessary CSS into your web pages and makes your chosen font file(s) available for use by visitors. It offers a wide selection of high quality fonts and has free and paid packages.

Typekit degrades gracefully so that anyone without JavaScript, or with a browser that doesn’t support the necessary features, will simply revert to your standard CSS rules. The reliance on JavaScript may be considered a problem but these days it is safe to assume that all visitors will have JavaScript enabled.

The two big advantages of Typekit are that you can rest assured the fonts are being used legally, and you’re given the option to reduce the file sizes by only including the styles and characters that you need.

How does it work?

First you’ll need to register with Typekit at typekit.com. They do offer a free account which may be all you need, and it’ll certainly be enough try the service and to see if it suits you or not. The free account does require that you show the Typekit logo on your website but that’s fully understandable and their ‘Personal’ plan isn’t a lot of money if you don’t want that restriction.

Once logged in, follow the guided process of adding your website and selecting your font(s). After adding each font you’ll be greeted with the option to define which CSS selectors it should be applied to, or you can manually add it to your own CSS file if you prefer. Next you should select only the specific styles and subsets you require to help reduce its size. After that click ‘Publish’ and you’re about done – all that left is to copy the supplied JavaScript code into the <head> section of your website.

The code that’s supplied by Typekit handles all of the browser quirks to ensure your fonts are seen by as many people as possible. It calls font files that are stored on high performing servers with a claimed uptime of 100%.

The process probably couldn’t be simpler and the results can really help your website stand out. I’m using the system on this website so you can see the effect right now and it’s something that I could never have done using image or flash replacement techniques.

Browser compatibility

If you’re wondering which precise browser support this method, they are as follows:

  • Internet Explorer: 5+
  • Firefox: 3.5+
  • Chrome: 4+
  • Safari: 3.1+
  • Opera: 10+

Some browsers do behave slightly different to others, for example Firefox starts by displaying text in a standard font and then switches to your custom one once the file has downloaded, whereas Webkit browsers will wait until the font is ready before it renders anything.

Also remember that the user must have JavaScript enabled.

My thoughts

Typekit is the first service of it’s kind that I’ve tried and I’m so happy with it that I haven’t even bothered to look any further. I have to admit that I’ve always been sceptical about the use of non-standard fonts on websites because of licensing issues and overly-large download sizes; however Typekit tackles both of these concerns superbly.

As a developer Typekit offers me a one-stop shop to point web designers towards when they want to use a custom font. They’re offered a wide variety of quality options in Typekit’s library and I don’t have worry about sourcing (and maybe buying) whichever font they choose. If I could ask for one more Typekit feature though, it would be a downloadable PDF showing the entire library (grouped by style) that I could share with designers I deal with.

With tools like this, now the only thing we have to fear is bad designers abusing fonts and making websites with illegible scripts! Such websites are easily ignored though and the benefits to us professionals greatly outweigh that nuisance. If I were a teacher I’d be awarding Typekit an A+ grade.

FirePHP: a quick start guide

Category : PHP, Programming, Quick tips

FirePHP is a useful tool that allows developers to output PHP debug messages directly into Firebug, so they’re displayed just like JavaScript console messages.

This guide assumes you’re using Firefox with the Firebug extension already installed.

Setting up FirePHP

With Firefox open, click Tools > Add-ons then search for “FirePHP” within the Get Add-ons tab and install the extension as usual.

Once it’s installed, and Firefox has restarted, open the Firebug window using the icon at the bottom-right of Firefox. Click on the Console and Net panels to ensure they’re both enabled. Also click on the blue FirePHP icon (near the top-left of Firebug) to make sure that’s enabled.

Now just make sure Firebug’s console is visible and you’re ready to start using FirePHP!

Getting your scripts ready

The FirePHP developers have written a library to make using their tool as easy as possible. Before you go any further download the FirePHPCore library from the this page and copy the included ‘FirePHPCore’ folder to somewhere that’s accessible by your website. Once you’ve done that you’re ready to include it in your PHP scripts.

The main thing to note about FirePHP is that it sends messages to Firebug using HTTP headers, so you cannot send anything to the browser (i.e. HTML output) until you’ve finished debugging with FirePHP. If you’ve got output_buffering enabled on your server this won’t be an issue but otherwise you will need to manually initiate a buffer from within your script using the ob_start() function.

<?php
require_once('FirePHPCore/fb.php');
ob_start();
?>

Note: this guide assumes you are using PHP5. If you are running PHP4 please use the relevant files in FirePHPCore and refer the notes on FirePHP’s website if you run into problems.

Simple debugging

The simplest way to get debug messages into Firebug is by using the log method, which accepts a variable and a label as it’s respective parameters. FirePHP will automatically output it in a suitable way regardless of it’s type, even if it’s an array or an instance of an object.

<?php
FB::log($myvar, 'My variable');  // the label is optional
?>

There are actually a few ways to call FirePHP’s methods but I find this approach the most straightforward. Don’t worry if you’re not familiar with the ‘FB::’ operator, it’s essentially just a convenient way of access the FirePHP object on a global scope. If you’d prefer to use more traditional object notation, or procedural code, scroll down to my final notes.

Specially formatted output

You’ll probably find that the log() method accounts for 90% of your FirePHP usage but sometimes it’s helpful to format a message depending on it’s context, like if you want to highlight a genuine error. The following output types are available.

<?php
FB::log('Typical debug message');
FB::info('Information message');
FB::warn('Script warning');
FB::error('Critical error');
?>

FirePHP can also output tables which, amongst other things, can come in useful for debugging database work. Here’s an example of a simple table sent to Firebug but it could just as easily have been created from some database results.

<?php
$table = array();
$table[] = array('First name', 'Surname');
$table[] = array('James', 'Smith');
$table[] = array('Robert', 'Johnson');
$table[] = array('Mary', 'Williams');
$table[] = array('Linda', 'Jones');
FB::table('Names', $table);
?>

It’s all very simple isn’t it!

Final notes

Debug information should never be visible on a live website so FirePHP makes to very simple to turn it’s output on and off. It’s important that you use this functionality as soon as you’ve finished debugging.

<?php
FB::setEnabled(false);
?>

If you’re not comfortable using the ‘FB::’ operator there are other ways of accessing FirePHP’s functionality. Very briefly these are as follows:

Basic object oriented calls

<?php
require_once('FirePHPCore/FirePHP.class.php');
$firephp = new FirePHP();
$firephp->log($myvar, 'My variable');
?>

Procedural calls

<?php
require_once('FirePHPCore/fb.php');
fb($myvar, 'My variable');
fb($table, 'Query results', FirePHP::TABLE);
?>

That’s all there is to using FirePHP. It’s so easy to get up and running, and even easier to use within your code so I hope you’ll give it a go. For me it’s made development so much easier because I no longer rely on inline debug messages that mess up page layouts.

Detecting your environment using server variables

Category : Apache, PHP, Programming, Quick tips, Server configuration

This article explains how you can use server variables to run websites on multiple servers without having to manually reconfigure key settings.

Like many web developers I use a single configuration file to define key website constants (file paths, database login etc.) and that file is included at the top of every page. Many of the constants can be sensitive to the working environment through so I may need one configuration for local development work and another when the website is uploaded to the live server.

If you’ve only ever done very basic server-side scripting you may be wondering why some settings need to vary. To show you the kind of things I’m taking about here’s an example of the first few lines of a typical configuration file in one of my websites.

<?
$environment = 'live';
if ($environment == 'live') {
  define('HTTPPATH', '/');
  define('ROOTPATH', '/home/sitedir/html/');
  define('DB_NAME', 'live_dbname');
  define('DB_USER', 'live_dbuser');
  define('DB_PASS', 'live_dbpass');
} else {
  define('HTTPPATH', '/sitedir/');
  define('ROOTPATH', '/home/ed/public_html/sitedir/');
  define('DB_NAME', 'dev_dbname');
  define('DB_USER', 'dev_dbuser');
  define('DB_PASS', 'dev_dbpass');
}
?>

So that snippet of code shows an if-statement which loads the relevant website settings depending on the value of $environment. There are a few ways to switch between different configurations.

Method 1: Manually set the correct configuration values

The most obvious way of switching configurations this is to manually change $environment whenever you upload the configuration file to the server. This is just something else to remember while editing your site though and is easily overlooked when you do a bulk upload to the server. It would be far better to automate the procedure.

Method 2: Rudimentary environment detection

Why bother manually updating the $environment when PHP can do it automatically? To do that we need a method of detecting where the site is running and that’s where the predefined $_SERVER array comes in.

You’re probably already familiar with $_SERVER but if not, all you need to know is that it’s an associative array containing information passed to PHP from the server itself. In the context of this article it contains useful information about the server address and script paths, for example here’s a few elements from a typical $_SERVER array.

KeyValue
HTTP_HOSTlocalhost
SERVER_NAMElocalhost
SERVER_ADDR::1
SERVER_PORT80
REMOTE_ADDR::1
DOCUMENT_ROOT/Users/ed/Sites
SCRIPT_FILENAME/Users/ed/Sites/index.php

We can compare one or more of those array elements to a predictable value in order to deduce the website’s current location. For example if I know the development version of my website is always run from the HTTP location of ‘localhost’ I could define $environment as follows:

if ($_SERVER['SERVER_NAME'] == 'localhost') {
  $environment = 'dev';
} else {
  $environment = 'live';
}

Now it doesn’t matter whether this file is running on my local development server or on the live server, it will automatically define the correct constants without me having to manually alter it every time it’s moved from one location to another.

Method 3: Environment detection using server variables

Using the default data provided in $_SERVER isn’t always ideal though because if the environment you’re testing against ever changes the website may fail. Also it can become a bit of pain writing unique new conditions for every website you develop – wouldn’t it be good if there were consistent values within $_SERVER that we could rely for a given server regardless of the website that’s being loaded?

As a real world example I am currently developing a single piece of code that will drive multiple websites, each with their own domain and living within their own directory on the server. It’s further complicated because the code must run on a live server, my office PC and my laptop (the latter two being development environments).

The tidiest way I’ve found to solve this problem is to set my own server variables, which is actually really simple.

When I configure a server now, I put the following code into the main Apache configuration but it could also be added to a specific site’s vhost file, or even a .htaccess file (assuming that it’s not synchronised with the development version).

SetEnv ENVIRONMENT devbox

Now in my configuration file I can check this value just as if it was any other server variable.

// select active environment
if ($_SERVER['ENVIRONMENT'] == 'devbox') {
  $environment = 'devbox';
} else if ($_SERVER['ENVIRONMENT'] = 'laptop';) {
  $environment = 'laptop';
} else {
  $environment = 'live';
}

To make life a little easier you may find that you don’t even need to add this server variable to your live server. In most cases just having it defined on the development server(s) will be sufficient.

You may be able to think of other uses for these custom server variables but I think these is amongst the most useful of them.