Posts Tagged ‘php’

How to test for any TextLinkAds first

Sunday, April 15th, 2012
Posted in Web Development · Tags: , ,

If you run Text Link Ads with the WordPress plugin, you might run into a situation where you want to check to see if there are any ads before you output them on your site. The reason, maybe that you have some heading or decoration near them that depends on them showing up. Well, I made a little hack to do just that.

/*homepage only*/
if(is_front_page() && function_exists("tla_ads"))
//hack to see if we have any ads available
global $textlinkads_object;
if (count($textlinkads_object->ads) > 0)
//output whatever heading or decoration you want here
tla_ads();//show ads

RSS Cron Job

Monday, December 14th, 2009
Posted in Web Development · Tags: ,

If you are on shared web host, you might not have the ability to run lots of cron jobs or be limited to a certain number per hour or day. You might know about the “Poor Man’s Cron Job”, which is basically not to run a task (usually caching some data or fetching a feed, api, etc.) in the background until someone visits a page. Which isn’t ideal, because often the page will be slow or sometimes it won’t be up to date until the second visit (if you run that task after outputting the cached data).

Well one way to get around this is to setup an RSS feed for the data you are caching or outputting and access it with a query string such as “?rss=2.0” or Then you can check to see if the RSS variable was passed and output a RSS feed with just enough data for a feed, no need to put sensitive data in there or anything. I would suggest putting in a ttl node in the RSS feed and set it to something the aggregators like Google Reader, should obey (that way they hit your page more or less frequently, depending on your needs). The item portion of an RSS feed only needs a title or a description, although its probably a good idea to put some kind of guid in there (check the RSS 2.0 spec for more info on creating RSS feeds).

Anyway here is some sample code. It isn’t complete but gives you an idea what I mean.

if ($_GET['rss'] == 2.0)
//create RSS 2.0 feed
header('Content-Type: text/xml');
$output = '<' . '?xml version="1.0"?' . '>' . "\n";
$output .= '<rss version="2.0">' . "\n";
$output .= '<channel>' . "\n";
//process your data and output it into RSS 2.0 format
$output .= '</channel>' . "\n";
$output .= '</rss>';
//process your data as normal

Then to make sure the page is hit often, place your RSS feed into Google Reader or Bloglines or some other RSS aggregator. Then your site will be visited often and forced to update. No one else really needs to know about your RSS feeds, unless you want them to be public as well.

phpBB 3.x RSS Hack

Monday, February 2nd, 2009
Posted in Web Apps · Tags: , ,

Where I work we use phpBB and I was surprised to see version 3 didn’t have built in RSS support. I found a mod, but it contained several files and required modifying several more files. I put together a hack that will pull the latest posts that are approved and non-reported; However, it will keep them unique to a topic. So if the last 5 posts are for a topic called “That is awesome”, it will only show a link to the last post on that topic and will look for the other latest posts from other topics.

It’s configurable with a item_limit (number of posts to pull) and word_limit (how long the description is). However the description is just the title for the last post, so it will most often be “RE: original post title” unless the user changes it when posting. I could of done another query in a loop to the table phpbb_posts and pulled out the corresponding post_text, but didn’t want to have the overhead. Although you could easily modify that in and cache the file for say 5 or 15 minutes. Think of this as a head start to get the feeds from your forum for whatever you plan to do with them. 😉


Calculating the Moon Phase

Sunday, September 7th, 2008
Posted in Web Development · Tags: ,

I was searching for a algorithm to get the phase of the moon, and unfortunately the Moon Phase Class on PHP Classes is inaccurate. With some searching I was able to find 2 sites that have code to pull it off (
Lunar Phase Calculator and Moon Phase Calculation.

I modified the latter (Moon Phase Calculation and used the first function listed on that page).

function moon_phase($year, $month, $day)
modified from
$c = $e = $jd = $b = 0;
if ($month < 3)
$month += 12;
$c = 365.25 * $year;
$e = 30.6 * $month;
$jd = $c + $e + $day - 694039.09; //jd is total days elapsed
$jd /= 29.5305882; //divide by the moon cycle
$b = (int) $jd; //int(jd) -> b, take integer part of jd
$jd -= $b; //subtract integer part to leave fractional part of original jd
$b = round($jd * 8); //scale fraction from 0-8 and round
if ($b >= 8 )
$b = 0;//0 and 8 are the same so turn 8 into 0
switch ($b)
case 0:
return 'New Moon';
case 1:
return 'Waxing Crescent Moon';
case 2:
return 'Quarter Moon';
case 3:
return 'Waxing Gibbous Moon';
case 4:
return 'Full Moon';
case 5:
return 'Waning Gibbous Moon';
case 6:
return 'Last Quarter Moon';
case 7:
return 'Waning Crescent Moon';
return 'Error';
$timestamp = time();
echo moon_phase(date('Y', $timestamp), date('n', $timestamp), date('j', $timestamp));

I haven’t been able to find out how to calculate the percentage for how lit up (full) the moon is yet though.

I converted the other code in another blog post. Calculating the Moon Phase Part 2

Found two WordPress plugins that have some code you might look at for moon phase calculation: ephemeris and moon phases

Free Weather Forecast

Tuesday, April 8th, 2008
Posted in Web Development · Tags: , , , ,

I noticed on the National Weather Service’s website they now allow you to grab the forecast by REST, whereas before they only supported SOAP requests. This makes grabbing the forecast much simpler than it was before.

If you use SOAP there are many methods to grab the data, but if you use REST there are only 2. With REST you can either use DWMLgen which lets you get a little more specific information or NDFDgenByDay which is a little simpler and lets you pick either 12 hour or 24 hour increments (so you can get each day broken in half as in day and night or the full day). The response is sent back as XML for either method so you can format the data how you like.

For the example we are doing, we are going to keep it simple and use a single location, NDFDgenByDay and a 24 hourly period. We will also set it up so that we send the longitude and latitude for Austin, TX, the current date as the start date and request 7 days worth of data.

Gallery2 vs Zenphoto vs Plogger

Tuesday, February 5th, 2008
Posted in Web Apps · Tags: , ,

Here I cover some of the features of the best open source PHP image gallery web applications.

Gallery 2

  • Multiple uploads via JavaScript (can add more file upload boxes)
  • Uploads by e-mail, ZIP or multiple image files
  • Configurable to run from multiple sites from one install
  • Reorder album via JavaScript
  • Ratings
  • Plugins available
  • Can’t protect original sizes of images


  • Multiple uploads via JavaScript (can add more file upload boxes)
  • Uploads by ZIP or multiple image files
  • Spam filter options (Akismet, CAPTCHA, SpamAssassin, …)
  • Reorder album via JavaScript
  • AJAX editing of albums and images
  • Ratings
  • Watermarks
  • Can’t protect original sizes of images (except with a watermark)
  • RSS feed


  • No multiple uploads via JavaScript (can’t add more file upload boxes)
  • Uploads by ZIP or single image files
  • Import from folder (you can FTP all images to a folder and have it import the images from that folder)
  • You can protect the original size images
  • RSS feed

All of these have a clean interface and design, search, EXIF data, subfolder/album creation, cruft-free URLs (for SEO), and comments (Gallery requires the comments plugin to be enabled).

It comes down to what your needs are, if you want something that can run on multiple sites Gallery 2 is the app to choose. If you have to protect your original size images you’ll want to use Plogger. I personally think Zenphoto has the most to offer and the best design out of the bunch, but they are all very well done. I went through all the ones on OpenSourceCMS and these were the best. Coppermine is popular but it’s too ugly and the admin is kind of confusing.

PHP Forms Class with 4 hour Video Tutorial

Monday, February 4th, 2008
Posted in Web Development · Tags:

Manuel Lemos has made a 4 hour video tutorial for his popular PHP Forms Generation and Validation class. Thankfully Google Video has a download link so you can watch it when you want. PHP Classes has quite a few other nice classes on their site, however the site is kind of confusing to use. Basically you have to register (which is free), then login and then pick what server to use (they balance their servers by doing this) then you can get whatever files you want. Anyone willing to make that long a tutorial is pretty cool in my book. 🙂 I haven’t used this yet, but it looks interesting.

Current Weather Conditions

Friday, February 1st, 2008
Posted in Web Development · Tags: , , ,

The National Weather Service provides Current Weather Conditions XML files for many cities in the US.

Here is some code for PHP5 (it uses SimpleXML) on doing this (assuming you’ve already grabbed the XML file from their site and have a way to cache it). It even has some code calculating the sunrise, sunset and civil twilight which PHP5 can do with date_sun_info() and since the XML file gives the date, latitude and longitude, you can calculate it dynamically.

if (file_exists('KADS.xml'))
$xmlstr = file_get_contents('KADS.xml');
$xml = simplexml_load_string($xmlstr);
$datetime = strtotime($xml->observation_time_rfc822);
$latitude = (float)$xml->latitude;
$longitude = (float)$xml->longitude;
$sun_info = date_sun_info(date('Y-n-j', $datetime), $latitude, $longitude);//calculate sunrise,sunset,...
echo '<ul id="current_conditions">';
echo '<li>' . date('l, F j, Y', $datetime) . '</li>';
echo '<li class="weather_loc">' . $xml->location . '</li>';
echo '<!--' . $xml->observation_time . '-->';
echo '<li><img src="' . $xml->icon_url_base . $xml->icon_url_name . '" alt="' . $xml->weather . '" /></li>';
echo '<li class="weather_temp"><strong>' . $xml->temp_f . '&deg;' . '</strong></li>';
echo '<li class="weather_sum"><strong>' . $xml->weather . '</strong></li>';
echo '<li>Wind: <strong>' . $xml->wind_dir . ' ' . round($xml->wind_mph) . ' mph</strong></li>';
echo '<li>Humidity: <strong>' . $xml->relative_humidity . '%</strong></li>';
if ($xml->heat_index_f != 'NA')
echo '<li>Heat Index: <strong>' . $xml->heat_index_f . '</strong></li>';
if ($xml->windchill_f != 'NA')
echo '<li>Windchill: <strong>' . $xml->windchill_f . '</strong></li>';
echo '<li>Barometer: <strong>' . $xml->pressure_in . '&quot;</strong></li>';
echo '<li>Visibility: <strong>' . $xml->visibility_mi . ' mi</strong></li>';
echo '<li>Dewpoint: <strong>' . $xml->dewpoint_f . '&deg;</strong></li>';
echo '<li class="weather_credit">weather by <a href="' . $xml->credit_URL . '" title="' . $xml->credit . '">NOAA</a></li>';
echo '</ul>';
echo '<ul id="sunrise_sunset">';
echo '<li>Sunrise: <strong>' . date('g:i a', $sun_info['sunrise']) . '</strong> <span class="civil_twilight">Civil Twilight: <strong>' . date('g:i a', $sun_info['civil_twilight_begin']) . '</strong></span></li>';
echo '<li>Sunrise: <strong>' . date('g:i a', $sun_info['sunset']) . '</strong> <span class="civil_twilight">Civil Twilight: <strong>' . date('g:i a', $sun_info['civil_twilight_end']) . '</strong></span></li>';
echo '</ul>';

You will probably want to cache that output once you have it formatted how you like.

CSS Class Based on Date

Wednesday, August 1st, 2007
Posted in Web Development · Tags: , , ,

I recently saw a tutorial on SimplePie’s site about using relative dates and I modified the function to output a CSS class rather than text. That way you can make newer stories bold, brighter, or bigger and older stories dimmed out or smaller. Use your imagination with CSS. 🙂

Here is the function

function create_age_css_class($date_sent)
$date_sent should be in the following format: YYYYMMDDHHMMSS
Based on doRelativeDate() By Garrett Murray,
$in_seconds = strtotime(substr($date_sent,0,8).' '.
$diff = time()-$in_seconds;
if ($diff < 86400)
$css_class = 'age_today';
else if ($diff < 604800)
$css_class = 'age_days';
else if ($diff < 1209600)
$css_class = 'age_week';
else if ($diff < 2630880)
$css_class = 'age_weeks';
$css_class = 'age_month';
return $css_class;

Here is how I call it

$data .= '<li><a href="'. $item->get_permalink();
$data .= ' class="' . create_age_css_class($item->get_date('YmdHis')) . '"';
$data .= '>';

You don’t have to use SimplePie for this function, but it’s what inspired me to modify it.

Now for an screenshot

Here is the HTML I used for that

<ul id="type3">
<li class="age_today">Lorem ipsum dolor sit amet</li>
<li class="age_days">Etiam iaculis nulla iaculis mauris</li>
<li class="age_week">Suspendisse at odio</li>
<li class="age_week">Nullam volutpat aliquam lacus</li>
<li class="age_weeks">Nunc dapibus eros vitae mauris rutrum laoreet</li>
<li class="age_weeks">Suspendisse sed nisl</li>
<li class="age_month">Nulla scelerisque gravida neque</li>
<li class="age_month">Leo imperdiet metus, ut adipiscing nisi lacus et pede</li>

And here is the CSS used

<style type="text/css">
body {font-family:Verdana, Arial, Helvetica, sans-serif; color:#000; background-color:#fff;}
ul {list-style:none;}
#type3 .age_days {font-size:150%; color:#555;}
#type3 .age_week {font-size:100%; color:#777;}
#type3 .age_weeks {font-size:80%; color:#999;}
#type3 .age_month {font-size:60%; color:#ccc;}

Added screenshot and sample CSS