Calculate Moon Phase Data with PHP

While developing ParaDB, I wanted to be able to calculate the phase of the moon given an arbitrary date and time. The only PHP software I found for this was the moon-phase class available from In my tests, however, I found it to be a bit less accurate than an equivalent Perl module I had used in the past called Astro::MoonPhase. So, I went ahead and just translated the Perl module to PHP.

The PHP version can be downloaded here. Feel free to expand on it, or rewrite it as a PHP class. If you use it in anything interesting, please let me know :)


The PHP moonphase functions work much like their Perl counterparts. Below is sample code returning a number of variables. This should be pretty familiar to those who have used the Astro::MoonPhase module:

require( '/2008/05/' );

$date = '2008-05-05';
$time = '20:36:00';
$tzone = 'PST';

// Usage: $data = phase( seconds_since_1970 );
$moondata = phase(strtotime($date . ' ' . $time . ' ' . $tzone));

$MoonPhase = $moondata[0];
$MoonIllum = $moondata[1];
$MoonAge = $moondata[2];
$MoonDist = $moondata[3];
$MoonAng = $moondata[4];
$SunDist = $moondata[5];
$SunAng = $moondata[6];

To add to this example, you could then translate the phase into an easy-to-read format:

$phase = 'Waxing';
if ( $MoonAge > SYNMONTH/2 ) {
$phase = 'Waning';
print "$phase\n";

You could even make this a bit more useful by using $MoonIllum:

// Convert $MoonIllum to percent and round to whole percent.
$MoonIllum = round( $MoonIllum, 2 );
$MoonIllum *= 100;
if ( $MoonIllum == 0 ) {
$phase = "New Moon";
if ( $MoonIllum == 100 ) {
$phase = "Full Moon";

print "Moon Phase: $phase\n";
print "Percent Illuminated: $MoonIllum%\n";

More information can also be found with the Astro::MoonPhase documentation. -- Moonphase Functions
moonphase.php -- Sample Code

That's it, enjoy :)

Update: This script is now available as a PHP class.


Dan said...

Is there a way for this script to also simply return the Moon's current RA/Dec coordinates with respect to the observer's location and time?
Could the coordinates and phasing be calculated a bit more precisely so it can work off local geographic lat+lon coordinates passed to it?

Eg in addition to returning the phase, i want to say "right now the moon is at RAx, DECy"
Once i have the RA/Dec coordinates then i can filter it through another script I have which converts it into local altitude + azimuth. (which is what I do for "fixed" stars+constellations at the moment, so the layman can be told exactly where to look up in the sky and in which direction)


dfeyer said...

I have done an oriented object version of your script:

Feel free to use it, clone it, an pull request ;)

AlekZonder said...

THIS is what i need! Thanks!

lulu said...

I like moon phases

Rankinstudio said...

I know it's been a while since this was posted. I have looked Everywhere for something like this! Thank you!!!!!!!!!!