If you want to do some graphics work within PHP you will need the GD library. It will take several steps of preparation before you can add this to PHP.

First you need to install X11, you can find this in the file InstallESD.dmg from the Mountain Lion installer package. How to find it, read this. This because you need to get an optional installer package if you want to use GD. Mount the disk image and install the file from Packages called X11redirect.pkg
To complete X11 you need to download and install the XQuartz X11 server.

Secondly you need to download the source code from the Freshmeat libjpeg project. Unpack the source code and then go into the newly created folder and execute the following commands:

export MACOSX_DEPLOYMENT_TARGET=10.8
./configure --enable-shared

Next follow with the commands:

make
sudo make install

To compile and install the library.

Next step is to recompile the php installation as described on this page: Compiling PHP.

The only change you need to make is to add:

--with-jpeg-dir=/usr/local/lib \
--with-png-dir=/usr/X11R6 \
--with-freetype-dir=/usr/X11R6 \
--with-xpm-dir=/usr/X11R6 \

To the configure statement and it will include this library for you.

For example:

./configure --prefix=/usr/local/php5 \
  --mandir=/usr/share/man \
  --infodir=/usr/share/info \
  --sysconfdir=/etc \
  --with-config-file-path=/etc \
  --with-zlib \
  --with-zlib-dir=/usr \
  --with-openssl \
  --without-iconv \
  --enable-exif \
  --enable-ftp \
  --enable-mbstring \
  --enable-mbregex \
  --enable-sockets \
  --with-mysql=mysqlnd \
  --with-pdo-mysql=mysqlnd \
  --with-mysqli=mysqlnd \
  --with-gd \
  --with-jpeg-dir=/usr/local/lib \
  --with-png-dir=/usr/X11R6 \
  --with-freetype-dir=/usr/X11R6 \
  --with-xpm-dir=/usr/X11R6 \
  --with-apxs2=/usr/local/apache2/bin/apxs