PHP Tutorials
Friday, December 2nd, 2011
This is a PHP CLI (Command Line Interface) script to monitor domain name availability. You must have PHP CLI compiled on the server to use this script, and have the proper permissions to set up a cron job to run it periodically. When a domain name becomes available for registration, the domain name is appended to a text file. This text file is then referred to so we don’t send more than one e-mail notice about that domain.
The PHP CLI script:
#!/usr/local/bin/php -q
<?php
// assign variables from command line input
$domain = $argv[1];
$email = $argv[2];
// this is a file to store the notified domains into
$file = "/path/to/ns_check.txt";
// validate input and execute command on success
if (!$domain || !$email) {
print("
nscheck 0.99+beta
usage:
nscheck [domain] [email]\n\n");
} else {
// prepare command variable
$command = "whois " . $domain . " | egrep -i 'NOT FOUND'";
// execute command
$return = @exec($command);
// assign file contents into an array
$notified = file($file);
// if return is not empty and email has not already been notified then send the email
if($return && !in_array($domain."\n", $notified)) {
$subject = 'Domain ' . $domain . ' Available for Registration';
$headers = 'From: Your Name <noreply@yourdomain.com' . "\r\n" .
'Return-Path: noreply@yourdomain.com' . "\r\n" .
'Reply-To: noreply@yourdomain.com' . "\r\n" .
'X-Mailer: SMTP/4.1';
$message = "The domain name " . $domain . " is now available for registration.\n\n";
mail($email, $subject, $message, $headers);
if (is_writable($file)) {
// open file for writing
if(!$handle = fopen($file, 'a')) {
echo "Cannot open file ($file)";
exit;
}
// write domain to our opened file.
if(fwrite($handle, $domain."\n") === FALSE) {
echo "Cannot write to file ($file)";
exit;
}
fclose($handle);
} else {
echo "The file $file is not writable";
}
}
}
?>
Be sure to edit “Your Name” and “noreply@yourdomain.com” to reflect your actual name and e-mail address. Also change “/path/to/ns_check.txt” to the correct file path for a text file to store the domain names in.
Place the above script in a file called “nscheck” and put it in /usr/local/sbin/ or another location. Be sure its permissions are set to executable. To run the script periodically, enter a cron job in your crontab:
0 11 * * * /usr/local/sbin/nscheck domaintocheck.com user@yourdomain.com
Once again, be sure to edit “domaintocheck.com” and “user@yourdomain.com” to reflect the domain you would like to check, and your e-mail address. If you placed the script somewhere besides /usr/local/sbin/ be sure and change the path in the above crontab entry to the proper path.
Posted in PHP Tutorials, Tutorials | 1 Comment »
Friday, May 6th, 2011
The following PHP function is to search for zipcodes within X miles away from the zipcode searched.
function getZipCodes($search, $miles_away) {
ini_set('memory_limit', '256M'); // set 128 MB memory limit
$lines = file($_SERVER["DOCUMENT_ROOT"].'/demos/zipcode-proximity-search/zipcodes.csv');
foreach($lines AS $line) {
$parts = explode("\",\"", $line);
$zipcode = str_replace('"', "", $parts[0]);
$latitude = $parts[1];
$longitude = $parts[2];
$type = $parts[5];
if($type != "MILITARY") {
if($zipcode == $search) {
$search_coords = array(
'zipcode' => $zipcode,
'lat' => $latitude,
'long' => $longitude
);
}
$zipcode_coords[] = array(
'zipcode' => $zipcode,
'lat' => $latitude,
'long' => $longitude
);
}
}
foreach($zipcode_coords AS $coords) {
if(calc_distance($coords, $search_coords) < $miles_away) {
$return[] = $coords['zipcode'];
}
}
return $return;
}
function calc_distance($point1, $point2) {
$radius = 3958; // Earth's radius (miles)
$pi = 3.1415926;
$deg_per_rad = 57.29578; // Number of degrees/radian (for conversion)
$distance = ($radius * $pi * sqrt(
($point1['lat'] - $point2['lat'])
* ($point1['lat'] - $point2['lat'])
+ cos($point1['lat'] / $deg_per_rad) // Convert these to
* cos($point2['lat'] / $deg_per_rad) // radians for cos()
* ($point1['long'] - $point2['long'])
* ($point1['long'] - $point2['long'])
) / 180);
return $distance; // Returned using the units used for $radius.
}
You would then call the function by using:
$zipcodes = getZipCodes($_POST['search'], "5.01");
You could then use this function to create your SQL query:
$sql = "SELECT id, zipcode FROM directory";
$total_query = mysql_query($sql) or die(mysql_error());
$total_numrows = mysql_num_rows($total_query);
if($_POST['doSearch'] && $searchby == "zipcode") {
$zipcodes = getZipCodes($_POST['search'], "5.01");
$i = "0";
foreach($zipcodes AS $zipcode) {
if($i == "0") $sql .= " WHERE "; else $sql .= " OR ";
$sql .= "zipcode = '" . $zipcode . "'";
$i++;
}
} elseif($_POST['doSearch']) {
$sql .= " WHERE " . $searchby . " LIKE '%" . $_POST['search'] . "%'";
}
You may download the CSV file of all zip codes here. If this post was helpful please leave a comment to let us know!
Tags: geocode, geocoding, google maps, maps, PHP Tutorials, search engine, search feature, search function, zip code, zip code proximity, zip codes
Posted in PHP Tutorials, Tutorials, Web Design Tutorials | No Comments »
Thursday, March 24th, 2011
In today’s tutorial we show you one way of displaying a list of the most popular posts in your WordPress template or sidebar. To do this you must first set up your site to use Google Analytics and make sure you’ve placed the code snippet in your theme’s footer.php. Next install the “Google Analytics Dashboard” plugin which can be found here:
http://wordpress.org/extend/plugins/google-analytics-dashboard/
We tested this with version 2.0.3 of the Google Analytics Dashboard wordpress plugin.
<?php
// options
$showposts = 3; // how many posts/pages to display?
$days = 30; // how many days back to calculate?
// do not edit below this line
$thispost = 1;
$start = date('Y-m-d', (time() - (60 * 60 * 24 * $days)));
$end = date('Y-m-d');
$login = new GADWidgetData(get_option('gad_auth_token'), get_option('gad_account_id'));
$ga = new GALib('client', $login->auth_token, '', '', $login->account_id);
$pages = $ga->pages_for_date_period($start, $end);
echo "<ul>";
foreach($pages as $page) {
$url = $page['value'];
$title = $page['children']['value'];
// ignore these page titles
$ignore = array(
'(not set)',
'Page Title 1',
'Page Title 2'
);
if(!in_array($title, $ignore)){
// list any strings you would like to remove from the titles
$remove = array(
" | Company Name",
" « Company Name"
);
$newtitle = str_replace($remove, "", $title);
echo '<li><a href="' . $url . '" rel="nofollow">' . $newtitle . '</a></li>';
$thispost++;
}
if($thispost > $showposts) break;
}
echo "</ul>";
?>
Tags: google, Google Analytics, html, php, Popular Posts, seo, web, web design, web development, web standards, web usability, website design, wordpress, wordpress plugins
Posted in PHP Tutorials, Tutorials, Web Design Tutorials, Wordpress Tutorials | 6 Comments »
Monday, April 12th, 2010
Using examples from Troy Wolf’s website, I’ve created a PHP script that will get Tasks for a user in Microsoft Exchange and create an ICS format calendar which can then be loaded (read only) into Mozilla Thunderbird.
<?php
require_once("class_http.php");
require_once("class_xml.php");
$exchange_server = "http://exchange.yourwebsite.com"; // no trailing slash
$exchange_username = "";
$exchange_password = "";
$h = new http();
$h->headers["Content-Type"] = 'text/xml; charset="UTF-8"';
$h->headers["Depth"] = "0";
$h->headers["Translate"] = "f";
$h->xmlrequest = '<?xml version="1.0"?>';
$h->xmlrequest .= <<<end
<g:searchrequest xmlns:g="DAV:">
<g:sql> SELECT "DAV:id" AS uid,
"DAV:href" AS url,
"DAV:creationdate" AS created,
"urn:schemas:httpmail:subject",
"urn:schemas:httpmail:textdescription",
"urn:schemas:calendar:location" AS location,
"http://schemas.microsoft.com/mapi/id/{00062003-0000-0000-C000-000000000046}/0x811c" AS completed,
"http://schemas.microsoft.com/mapi/id/{00062003-0000-0000-C000-000000000046}/0x00008105" AS duedate,
"http://schemas.microsoft.com/mapi/id/{00062003-0000-0000-C000-000000000046}/0x00008104" AS start
FROM Scope('SHALLOW TRAVERSAL OF "/exchange/$exchange_username/Tasks"')
WHERE "DAV:contentclass" = 'urn:content-classes:task'
AND CAST("http://schemas.microsoft.com/mapi/id/{00062003-0000-0000-C000-000000000046}/0x811c" AS "boolean") = CAST(false AS "boolean")
ORDER BY "DAV:creationdate" DESC
</g:sql>
</g:searchrequest>
END;
if (!$h->fetch($exchange_server."/exchange/$exchange_username/Tasks", 0, null, $exchange_username, $exchange_password, "SEARCH")) {
exit();
}
$x = new xml();
if (!$x->fetch($h->body)) {
exit();
}
function format_time($date_string) {
$date = str_replace("-", "", $date_string);
$date = str_replace(":", "", $date);
$date = substr($date, 0, -5);
return $date;
}
function format_time_z($date_string) {
$date = str_replace("-", "", $date_string);
//$date = str_replace(".000Z", "Z", $date);
$date = str_replace(":", "", $date);
$date = substr($date, 0, -5);
return $date."Z";
}
header("Content-Type: text/x-vCalendar");
header("Content-Disposition: inline; filename=tasks.ics");
echo "BEGIN:VCALENDAR\n";
echo "VERSION:2.0\n";
echo "PRODID:-//Mozilla.org/NONSGML Mozilla Calendar V1.1//EN\n";
echo "METHOD:PUBLISH\n";
echo "BEGIN:VTIMEZONE\n";
echo "TZID:America/New_York\n";
echo "X-LIC-LOCATION:America/New_York\n";
echo "BEGIN:DAYLIGHT\n";
echo "TZOFFSETFROM:-0500\n";
echo "TZOFFSETTO:-0400\n";
echo "TZNAME:EDT\n";
echo "DTSTART:19700308T020000\n";
echo "RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=2SU;BYMONTH=3\n";
echo "END:DAYLIGHT\n";
echo "BEGIN:STANDARD\n";
echo "TZOFFSETFROM:-0400\n";
echo "TZOFFSETTO:-0500\n";
echo "TZNAME:EST\n";
echo "DTSTART:19701101T020000\n";
echo "RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=1SU;BYMONTH=11\n";
echo "END:STANDARD\n";
echo "END:VTIMEZONE\n";
foreach($x->data->A_MULTISTATUS[0]->A_RESPONSE as $num => $event) {
$UID = $event->A_PROPSTAT[0]->A_PROP[0]->UID[0]->_text;
$SUMMARY = $event->A_PROPSTAT[0]->A_PROP[0]->D_SUBJECT[0]->_text;
$DESCRIPTION = $event->A_PROPSTAT[0]->A_PROP[0]->D_TEXTDESCRIPTION[0]->_text;
$CREATED = format_time_z($event->A_PROPSTAT[0]->A_PROP[0]->CREATED[0]->_text);
$STAMP = format_time_z($event->A_PROPSTAT[0]->A_PROP[0]->START[0]->_text);
$START = format_time($event->A_PROPSTAT[0]->A_PROP[0]->START[0]->_text);
$DUE = format_time($event->A_PROPSTAT[0]->A_PROP[0]->DUEDATE[0]->_text);
$COMPLETED = $event->A_PROPSTAT[0]->A_PROP[0]->COMPLETED[0]->_text;
echo "BEGIN:VTODO\n";
echo "CREATED:$CREATED\n";
echo "LAST-MODIFIED:$START\n";
echo "SUMMARY:$SUMMARY\n";
echo "DTSTAMP:$START\n";
echo "UID:$UID\n";
echo "SUMMARY:$SUMMARY\n";
echo "DTSTART;TZID=America/New_York:$START\n";
echo "DUE;TZID=America/New_York:$DUE\n";
# echo "X-MOZ-GENERATION:2\n";
# echo "DESCRIPTION:$DESCRIPTION\n";
echo "END:VTODO\n";
#var_dump($x); break; die();
}
echo "END:VCALENDAR";
// You can print out the response to help troubleshoot.
?>
Tags: caldav, calendar, exchange, ical, ics, microsoft, php, webdav
Posted in PHP Tutorials, Tutorials, Web Design Tutorials | No Comments »