Setting up PHP & MySQL on OS X 10.6 Snow Leopard

5th October 2009

With OS X 10.6, Apple ships PHP 5.3 with PEAR, GD and PDO_MYSQL out of the box. Also, everything is now 64bit. This means that the entire effort required to get a working PHP dev environment for my work is now much easier.

/usr/local

Ensure that the following directories exist:

sudo mkdir /usr/local/include
sudo mkdir /usr/local/bin
sudo mkdir /usr/local/lib
sudo mkdir -p /usr/local/man/man1

MySQL

  1. Download the 64bit version of MySQL 5.0.x for OS X 10.5 from mysql.com and install the pkg, the startup item and the pref pane.
  2. Add /usr/local/mysql/bin to the path: vim ~/.bash_profile and add:
    export PATH=~/bin:/usr/local/bin:/usr/local/mysql/bin:$PATH
    export EDITOR=vim
    

    at top of file. (Note that we set EDITOR whilst we are here so that svn is happy!)

  3. Set up MySQL root password:
    mysqladmin -u root password {new-password}
    mysqladmin -u root -p{new-password} -h localhost password {new-password}
    mysqladmin -u root -p reload
    

    Quit Terminal to flush the history to file. Restart Terminal and remove the history file: rm .bash_history so that {new-password} isn't in plain text on the disk.

Apache

  1. cd /etc/apache2
  2. sudo vim httpd.conf
  3. Find #LoadModule php5_module libexec/apache2/libphp5.so and remove the leading #
  4. Find AllowOverride None within the <Directory "/Library/WebServer/Documents">section and change toAllowOverride All so that .htaccess files will work.
  5. Restart Apache: sudo apachectl restart
  6. Open Finder and navigate to /Library/WebServer/Documents/
  7. Create a new folder called "orig" and place all files currently in the Documents folder into it.
  8. Create a new file called info.php with <?php phpinfo(); inside it.
  9. Use Safari to navigate to http://localhost/info.php and check that the PHP version is displayed (5.3.0 at the time of writing).

php.ini

  1. cd /etc
  2. sudo cp php.ini.default php.ini
  3. sudo chmod ug+w php.ini
  4. sudo chgrp admin php.ini
  5. vim php.ini (assuming your user is a member of the admin group) and change settings appropriately. Change:
    error_reporting  =  E_ALL | E_STRICT
    display_errors = On
    html_errors = On
    extension_dir = "/usr/lib/php/extensions/no-debug-non-zts-20090626"
    

    (I like to see my xdebug errors in bright orange!)
    Also, change all instances of /var/mysql/mysql.sock to /tmp/mysql.sock

Xdebug

Can't have a PHP development environment without xdebug!

  1. sudo pecl install xdebug
  2. Edit /etc/php.ini and add
    zend_extension="/usr/lib/php/extensions/no-debug-non-zts-20090626/xdebug.so"

    after the other extension lines.

  3. Restart apache: sudo apachectl restart and check in the phpinfo that xdebug is now loaded.

It all works on this machine, anyway :)

Changing OS X Terminal colours when ssh'ing into a server

2nd October 2009

I recently discovered that iTerm has bookmarks so you can set up a bookmark to ssh into a server and change the colours of the window. This makes it easy to remember which terminal window is for which server.

Thinking about it, I wondered if you could change the colours of the standard OS X Terminal via AppleScript. Inpired by Red Sweater's Random Color Terminal post, I wrote some code to automatically change the Terminal colour whenever I ssh into a known server.

As I know PHP and PHP is installed on OS X, I used that :)

The key to controlling AppleScript via PHP is the osascript command line application. The code I need specifically is:


system("osascript -e 'tell application \"Terminal\"
            set targetWindow to window 1
            set background color of targetWindow to {" $bgColour "}
            set cursor color of targetWindow to {" $fgColour "}
            set normal text color of targetWindow to {" $fgColour "}
            set bold text color of targetWindow to {" $fgColour "}
        end tell' ");

where $bgColour and $fgColour are comma separated strings containing three numbers between 0 and 65535 as AppleScript colours are 16 bit.

We start by getting a command line solution where we can type:
termcolour.php white
or
termcolour.php 00ff00
or
termcolour.php 255 0 0

and have the background colour of the Terminal change to the colour we have asked for.

TerminalColour class

Firstly we need a class that can change the colour of the Terminal window for us and also translate colours from 8bit RGB to 16bit RGB. As it is also useful to be able to specify colours by name, eg. "white", we'll add a lookup system too. I store this in /usr/local/bin.

This class is quite long, so this is a snippet:

<?php
class TerminalColour
{
    protected $_colour = array('255','255','255');
    
    /**
     * List of colours
     */
    protected $_colours = array(
        'white' => 'ffffff',
        'black' => '000000',
        // etc
    );
    

    /**
     * Set the colour of the topmost Terminal window using AppleScript
     *
     * $bgColour may be either an array of red, green, blue (8 bit) or a 
     * hex string or a string that matches an entry in the _colours lookup 
     * list.
     *
     * If $fgColour is null, then automatically use either black or
     * white based on brightness of $bgColour.
     *
     * @param array|string $bgColour
     * @param array|string $fgColour
     * @return array
     */
    function setTerminalColour($bgColour=null$fgColour=null) 
    {
        if(!is_null($bgColour)) {
            $this->setColour($bgColour);
        }
        $bgColour $this->getColour();
        
        
        // convert from 8 bit colour numbers to 16 bit ones
        $bgColour $this->convertTo16bit($bgColour);
            
        if($fgColour === null) {
            $fgColour $this->getFgColour($bgColour);
        } else {
        }
        
        $bgColour implode(','$bgColour);
        $fgColour implode(','$fgColour);
    
        system("osascript -e 'tell application \"Terminal\"
            set targetWindow to window 1
            set background color of targetWindow to {" $bgColour "}
            set cursor color of targetWindow to {" $fgColour "}
            set normal text color of targetWindow to {" $fgColour "}
            set bold text color of targetWindow to {" $fgColour "}
        end tell' ");
    }
}

As you can see, there's a variety of helper methods that I've not show here. setColour() is the where we map from the types of input that the user will provide to an array. Other that that, it's fairly self-explanatory.

Change colour from the command line

Now we need a script that uses our class. termcolours.php, that I can execute from the command line to change any given Terminal window to a new background colour.

termcolour.php is stored in /usr/local/bin and has execute permissions set using chmod a+x termcolour.php from the command line:

#!/usr/bin/php
<?php
include dirname(__FILE__) . '/TerminalColour.php';

process($argc$argv);
exit;

function process($argc$argv)
{
    if($argc == 1) {
        echo <<<EOT
TerminalColour: Set the background colour of a Terminal.app window 
USAGE: 
    1. termcolour.php {r} {g} {b} 
        ({r}, {g}, {b} are between 0 and 255)
    2. termcolour.php {hexvalue}
        ({hexvalue} assumed to be from 000 to fff or 00000 to ffffff)

EOT;
        exit;
    }
    
    $tc = new TerminalColour();
    if($argc == 4) {
        // called with three arguments - treat as rgb values (0-255)
        array_shift($argv); // remove name of script
        $tc->setTerminalColour($argv);
    }
    
    if($argc == 2) {
        // called with one argument - either a lookup or a hex value
        $tc->setTerminalColour($argv[1]);
    }
}

Again, not complicated. we check number of arguments to the script and if there are none, we display a help message. If there are exactly 1 or 3, then we call TerminalColour::setTerminalColour() appropriately.

Hooking into SSH

Lastly we hook into ssh and change the colour based on the server name.

To do this, I've used a simple shell script and modified termcolours.php to add some additional colour look up entries.

/usr/local/bin/sshcolours.sh:
/usr/local/bin/termcolour.php $@
/usr/bin/ssh $@
/usr/local/bin/termcolour.php white

termcolour.php


//...
    
    $tc = new TerminalColour();

    // add colours for servers
    $colourLookup $tc->getLookupColours();
    $serverColours = array(
        'server1' => $colourLookup['darkblue'],
        'server2' => $colourLookup['red'],
        'server3' => 'C4DFC3',
    );
    $tc->addToLookupColours($serverColours);

    if($argc == 4) {
//...

(not a large change!)

finally, we add an alias to ~/.bash_profile:


alias s=sshcolours.sh

That's it! I can now type:

	s server1

and Terminal's background colour turns blue and I'm ssh'd into server 1.

Sometimes I just type termcolour.php darkred to remind myself that this terminal window is doing something long-running and not to accidentally close it...

This is a zip file of the relevant files.

Setting up PHP on OS X Leopard

5th March 2009

In the vein of some of Lorna's articles, this is more a note for myself than anything else. Not everything is explained in detail as it assumes you know how to use a command line...

These are the steps I take to get the Apple supplied PHP working with GD, PDO_MySQL and Xdebug working on OS X 10.5.

/usr/local

Ensure that the following directories exist:

    sudo mkdir /usr/local/include
    sudo mkdir /usr/local/bin
    sudo mkdir /usr/local/lib
    sudo mkdir -p /usr/local/man/man1

Run Apache in 32 bit mode

This saves us having to compile our own MySQL as MySQL doesn't offer a "fat" binary

  1. cd /System/Library/LaunchDaemons
  2. sudo vim org.apache.httpd.plist
  3. Immediately after the line containing <array> add:
        <string>arch</string>
        <string>-i386</string>
    
  4. Reboot

MySQL

  1. Download the 32bit version of MySQL 5.0.x for OS X 10.5 from mysql.com and install the pkg, the startup item and the pref pane.
  2. Add /usr/local/mysql/bin to the path: vim ~/.bash_profile and add:
        export PATH=~/bin:/usr/local/bin:/usr/local/sbin:/usr/local/mysql/bin:$PATH
        export EDITOR=vim
    

    at top of file. (Note that we set EDITOR whilst we are here so that svn is happy!)

  3. Set up MySQL root password:
        mysqladmin -u root password {new-password}
        mysqladmin -u root -p{new-password} -h localhost password {new-password}
        mysqladmin -u root -p reload
    

    Quit Terminal to flush the history to file. Restart Terminal and remove the history file: rm .bash_history so that {new-password} isn't in plain text on the disk.

  4. Set the correct socket information for PHP. Ensure MySQL is running via the System Preferences panel then:
        sudo mkdir /var/mysql
        sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock
    

Rest of Apache setup

  1. cd /etc/apache2
  2. sudo vim httpd.conf
  3. Find #LoadModule php5_module libexec/apache2/libphp5.so and remove the leading #
  4. Find AllowOverride None within the <Directory "/Library/WebServer/Documents">section and change toAllowOverride All so that .htaccess files will work.
  5. Restart Apache: sudo apachectl restart
  6. Open Finder and navigate to /Library/WebServer/Documents/
  7. Create a new folder called "orig" and place all files currently in the Documents folder into it.
  8. Create a new file called info.php with <?php phpinfo(); inside it.
  9. Use Safari to navigate to http://localhost/info.php and check that the PHP version is displayed (5.2.6 at the time of writing).

php.ini

  1. cd /etc
  2. sudo cp php.ini.default php.ini
  3. sudo chmod ug+w php.ini
  4. sudo chgrp admin php.ini
  5. vim php.ini (assuming your user is a member of the admin group) and change settings appropriately. Change:
        error_reporting  =  E_ALL | E_STRICT
        extension_dir = "/usr/lib/php/extensions/no-debug-non-zts-20060613"
    

    You must set the extension dir correctly. (Commenting the line out also works...)

PHP extensions

The supplied PHP doesn't come with pdo_mysql, pear or gd, so fix it.

  1. Download the correct version of PHP from http://www.php.net/releases/. (5.2.6 at time of writing)
  2. Create a directory called src in your home directory and unpack the PHP source. This creates /Users/rob/src/php-5.2.6/ in my case.

pdo_mysql

  1. cd ~/src/php-5.2.6/ext/pdo_mysql.
  2. phpize
  3. MACOSX_DEPLOYMENT_TARGET=10.5 \
    CFLAGS='-O3 -fno-common -arch i386' \
    LDFLAGS='-O3 -arch i386' \
    CXXFLAGS='-O3 -fno-common -arch i386' \
    ./configure --prefix=/usr --with-pdo-mysql=/usr/local/mysql
  4. make
  5. sudo make install
  6. Edit /etc/php.ini and find the extension_dir line and add after it:
        extension=mysql.so
  7. Restart apache: sudo apachectl restart and check in the phpinfo that pdo_mysql is now loaded.

GD

Installing GD onto the stock PHP install that is supplied with OS X is slightly more complicated than you'd expect because you need to install libjpeg first.

Libjpeg

Libjpeg is available from the Independent JPEG Group.

  1. Download the source code: http://www.ijg.org/files/jpegsrc.v6b.tar.gz
  2. extract to ~/src
  3. cd ~/src/jpeg-6b
  4. cp /usr/share/libtool/config.* .
  5. ./configure --enable-shared
  6. sudo make install
  7. Libjpeg is now installed in /usr/local/lib

GD extension

  1. cd ~/src/php-5.2.6/ext/gd
  2. phpize
  3. MACOSX_DEPLOYMENT_TARGET=10.5 \
    CFLAGS='-O3 -fno-common -arch i386' \
    LDFLAGS='-O3 -arch i386' \
    CXXFLAGS='-O3 -fno-common -arch i386' \
    ./configure --with-zlib-dir=/usr --with-jpeg-dir=/usr/local/lib --with-png-dir=/usr/X11R6 --with-freetype-dir=/usr/X11R6 --with-xpm-dir=/usr/X11R6
  4. make
  5. sudo make install
  6. Edit /etc/php.ini and find the extension_dir line and add after it:
        extension=gd.so
  7. Restart apache: sudo apachectl restart and check in the phpinfo that GD is now loaded.

PEAR

  1. cd ~/src/.
  2. curl http://pear.php.net/go-pear > go-pear.php
  3. Accept defaults, except for installation prefix (1) should be /usr/local
  4. Check that the include_path in /etc/php.ini is correct and includes the PEAR directory (/usr/local/PEAR).

Xdebug

Can't have a PHP development environment without xdebug!

  1. sudo pecl install xdebug
  2. Edit /etc/php.ini and add
        zend_extension="/usr/lib/php/extensions/no-debug-non-zts-20060613/xdebug.so"

    after the other extension lines.

  3. Restart apache: sudo apachectl restart and check in the phpinfo that xdebug is now loaded.

PHPUnit

  1. sudo pear channel-discover pear.phpunit.de
  2. sudo pear install phpunit/PHPUnit

It all works on this machines, anyway :)

Updatesee Marc Liyanage's PHP5 packages

Uninstalling MySQL on Mac OS X Leopard

11th September 2008

To uninstall MySQL and completely remove it (including all databases) from your Mac do the following:

  • Use mysqldump to backup your databases to text files!
  • Stop the database server
  • sudo rm /usr/local/mysql
  • sudo rm -rf /usr/local/mysql*
  • sudo rm -rf /Library/StartupItems/MySQLCOM
  • sudo rm -rf /Library/PreferencePanes/My*
  • edit /etc/hostconfig and remove the line MYSQLCOM=-YES-
  • rm -rf ~/Library/PreferencePanes/My*
  • sudo rm -rf /Library/Receipts/mysql*
  • sudo rm -rf /Library/Receipts/MySQL*

The last two lines are particularly important as otherwise, you can't install an older version of MySQL even though you think that you've completely deleted the newer version!

On Mail.app

22nd March 2008

As I mentioned a while ago, I'm now using a MacBook Pro. All is going well, and I like Mail.app's search and data detectors very much. There are some niggles though that I miss from Thunderbird. My top 3 are:

* GPG integration (Thunderbird's Enigmail)
* Mail.app's insistence on attached PDFs and images inline
* Filing mails to arbitrary folders using the keyboard (Thunderbird's nostalgy)

It turns out that there are solutions to all three issues for OS X's Mail.app:

* GPGMail from Sente. (Not for Leopard, yet though)
* Mail Attachments Iconizer from Lokiware
* MsgFiler from tow.

I had found GPGMail a while ago and I"m looking forward to the Leopard release. In the meantime, I am getting by using the Services->GPG menu. I only learnt about the other two by accident.

Lokiware is sponsoring the Daring Fireball RSS feed this week and John Gruber's write up about this event, pointed at Dan Frakes’s Macworld article which not only persuaded me to download Mail Attachments Iconizer also mentioned MsgFiler too.

I've bought both! Clearly sponsoring DF's RSS feed is worthwhile :)

Now, I'm trying to decide if I should buy Yojimbo...

Cure for BSS announced!

23rd February 2008

Cal Evans has announced a cure for Blank Stare Syndrome!

You know the problem: you're in a conversation and someone mentions something about a new technology that you haven't heard of. Your eyes glaze and you have that Blank Stare...

Sixty Second Tech is the solution. Once a week, it will deliver a short podcast (presumably about 60 seconds long!) that explains one technological concept per episode that you (or your less-techy friends!) need to know.

Head on over there and subscribe to the RSS Feed now - or wait for it to turn up on iTunes shortly.

TaskPaper

18th November 2007

One of the apps that I've found that I'm using daily is TaskPaper from Hog Bay Software. It's a brilliantly simple idea where all it does is format up a standard text file to make it easier to use as a todo list.

You just start each item with a dash and it will automatically provide a checkbox next to the item. When you tick the checkbox, then a tag, @done, is added to the end of the line and it is crossed out. To aid organisation, any title that ends in a colon is automatically made bold and considered a project. Tags start with a @ symbol and can be used for filtering. For instance, you can get it to display all tasks with the tag of @town to provide a list of items to be done when you next go into town.

All in all, TaskPaper is very simple and very easy to use. You start it up and you can get going straight away.

Obviously, there are a few niggles! Three that I've noticed are:

  • Dragging and dropping of tasks to reorder isn't as smooth as it could be as TaskPaper tends to put the task you are moving into the same line as the task you are trying to insert above.
  • If I've completed all sub-tasks, it would be nice if it automatically marked the parent task as done too. In reverse, it would be handy if it would auto-mark-done all child tasks when I mark their parent task as done.
  • The context menu contains items that don't make sense, such as font and colours.

Niggles, really is the word, isn't it?! I need to stress the application more so that I can find an important thing to complain about!

Hog Bay Software is run by Jesse, who is a really nice guy as he even answered my emailed bug report even though I was just a trial user. I've since bought the product as to my mind it's well worth the money.

I'm now looking for a "diary" type program that will present me with a blank page every day automatically. Bonus points if it allows tagging of pages to help me find stuff I've stored and I'd also like it to store its files in RTF files or similar so that I can take them to Pages with no hassle. So far, I've looked at Journler, Jotter and MacJournal so far, but all require me to start a new entry manually.

svn and case-insentive file systems

10th November 2007

Another one to chalk up to a doh! moment...

I'm checking out my wife's website to my new MacBook and get this error message:

svn: In directory 'website/gallery/piccies'
svn: Can't move source to dest
svn: Can't move 'website/gallery/piccies/.svn/tmp/prop-base/IMG_0013-thumb.jpg.svn-base' to 'website/gallery/piccies/.svn/prop-base/IMG_0013-thumb.jpg.svn-base': No such file or directory

I'm pretty sure that there's no problem with the subversion repository as I've been using it for months with no problem so I asked a friend to check it out on his Windows box... which failed with the same error. We thought at first that linux was allowing something illegal to occur which Windows and Macs weren't. Then we thought about the other differences between Linux and Windows/Mac OS X.

After a while. It turns out that there are two files in the directory: IMG_0013.jpg and IMG_0013.JPG. One svn mv command later and the problem is solved.

It would have been nice to have had a better error message though!

The move to Mac

9th November 2007

A couple of days after Leopard came out, my wife and I found ourselves in the Apple store in Solihull and came away with an iMac for her and a MacBook Pro for me.

The main reasons we have been interested in Macs recently are:

  • Disappointed with Vista on my wife's brand new computer
  • Disappointed with our last two Inspiron laptops
  • Sleep that works
  • The hardware looks good!
  • Unix in the terminal

Interestingly, the biggest benefit we've noticed since purchase is how quiet they are. We didn't realise how noisy those PCs under the desk actually were til we got rid of them.

The biggest challenge has been adapting to the keyboard. The @, " and \ keys in particular are in the "wrong" place, and carat navigation is maddeningly inconsistent between applications. I've worked out that Option+left/right move per word and command+left/right is supposed to move to the start/end of the line. Command+up/down usually moves to the top and bottom of the document, but I haven't found page up/down yet but suspect it has something to do with function option and up,down left or right!

We haven't worked out when we need to quit applications vs just closing the window which leaves the app running.

PHP 5.2.4 was installed by Apple and just needed turning on in httpd.conf (it's in /etc... did I mention how nice having Unix underneath is?!) What's odd is that PDO isn't there and so I suspect that I'm going to have to compile my own PHP at some point.