Moon phase calculator
This is a simple PHP class to calculate the phase of the moon for any given time. It is based on the excellent Moontool for Windows application.
Usage
Include the moon-phase.php file in your script, and then simply create an instance of the moonphase class, supplying a UNIX timestamp for when you want to determine the moon phase. The following variables will be created in the resulting object, which you can then access from your script:
phase: the terminator phase angle as a fraction of a full circle (i.e., 0 to 1)illum: the illuminated fraction of the Moon (0 = New, 1 = Full)age: the age of the Moon, in daysdist: the distance of the Moon from the centre of the Earthangdia: the angular diameter subtended by the Moon as seen by an observer at the centre of the Earthsundist: the distance to the Sun in kilometressunangdia: the angular diameter subtended by the Moon as seen by an observer at the centre of the Earth
Demo
Here is some moon phase data for the present moment.
Coding example
Determine the current age of the moon in days, whether it is waxing or waning, and its distance from Earth:
<?php
include 'moon-phase-class.php';
// create an instance of the class, and use the current time
$moon = new moonphase( time() );
$age = round($moon->age, 1);
$stage = $moon->phase < 0.5 ? 'waxing' : 'waning';
$distance = round($moon->dist, 2);
echo "The moon is currently $age days old, and is therefore $stage. ";
echo "It is $distance km from the centre of the Earth.";
?>
The script is available under the GNU Public License. It requires PHP 5. If you have any problems or suggestions, feel free to contact me.