Switch between any installed php version in MAMP

By default, the MAMP’s free UI only lets you choose between php 5.3 and 5.4.
Developing and patching on hosting platforms that don’t or can’t install the latest version as soon as its available makes it useful to be able to choose *any* of the php versions MAMP makes available.

I could’ve just paid for MAMP Pro, but the pleasure of scripting it myself and revising sed and awk in the process couldn’t be missed.

First, awk the currently active php version from MAMP’s httpd.conf – splitting the matched line with a “/” delimiter:

awk -F '/'

then extracting the 6th “chunk”:

{ print $6 }

Then list the php version directories in the MAMP folder, using sed to erase the bits of the wide directory listing we don’t need, finally sorting the result in proper version order:

versionlist=`ls -d /Applications/MAMP/bin/php/php5.* | sed 's/\/Applications\/MAMP\/bin\/php\///g' | sort -t. -k 1,1n -k 2,2n -k 3,3n`

Full listing:

#!/bin/bash

# Get current php version
currentphp=`awk -F '/' '/LoadModule php5_module/ { print $6 }' /Applications/MAMP/conf/apache/httpd.conf`
 
# include the CocoaDialog app for Platypus' benefit.
CD="CocoaDialog.app/Contents/MacOS/CocoaDialog"
 
# Get the list of currently installed php versions in the MAMP hierarchy.
versionlist=`ls -d /Applications/MAMP/bin/php/php5.* | sed 's/\/Applications\/MAMP\/bin\/php\///g' | sort -t. -k 1,1n -k 2,2n -k 3,3n`
 
# Create the drop-down menu.
rv=`$CD dropdown --string-output  --text "The drop-down lists all php versions on this system. $currentphp is active. Which do you want to enable?" --items $versionlist --button1 "Ok"` 
 
# extract the version number from the drop-down result
chosen=`echo $rv | awk -F' ' '{ print $2 }'`
 
# Replace the decimal points with slashes
fixed=`echo $chosen | sed 's/\./\\\./g'` 
 
# Overwrite httpd.conf's existing php version with the new, chosen one.
sed -i 'BAK' -E "s/php5\.[0-9]{1,}\.[0-9]{1,}/$fixed/" /Applications/MAMP/conf/apache/httpd.conf
 
# Restart apache *gracefully*
/Applications/MAMP/bin/apache2/bin/apachectl graceful
 
# Re-check the current php version in httpd.conf *just in case*   
newphp=`awk -F '/' '/LoadModule php5_module/ { print $6 }' /Applications/MAMP/conf/apache/httpd.conf`
 
# ...and tell the user what the current version is. 
$CD ok-msgbox --no-cancel --text "$newphp is now enabled."

Bundling it into a simple [cmd][space] app with Platypus was as easy as including the CocoaDialog package and adding a few messages:

Screen shot 2013-06-11 at 17.25.16

Used in combination with my command line php version selector, I can test against any of 8 different php versions with minimum effort.

One thought on “Switch between any installed php version in MAMP”

Leave a Reply

Your email address will not be published. Required fields are marked *