Archive

Archive for April, 2009

PHP Array Of Canadian States

April 23rd, 2009 2 comments

Use the following array to print out a list of Canadian states, also know as provinces.

$canadian_states = array( 
    "BC"=>"British Columbia", 
    "ON"=>"Ontario", 
    "NL"=>"Newfoundland and Labrador", 
    "NS"=>"Nova Scotia", 
    "PE"=>"Prince Edward Island", 
    "NB"=>"New Brunswick", 
    "QC"=>"Quebec", 
    "MB"=>"Manitoba", 
    "SK"=>"Saskatchewan", 
    "AB"=>"Alberta", 
    "NT"=>"Northwest Territories", 
    "NU"=>"Nunavut"
    "YT"=>"Yukon Territory");

Here is the same array, but with the French versions of the states.

$canadian_states = array( 
    "AB"=>"Alberta"
    "BC"=>"Colombie-Britannique"
    "MB"=>"Manitoba"
    "NB"=>"Nouveau-Brunswick"
    "NL"=>"Terre-Neuve-et-Labrador"
    "NS"=>"Nouvelle-Écosse"
    "NT"=>"Territoires du Nord-Ouest"
    "NU"=>"Nunavut"
    "ON"=>"Ontario"
    "PE"=>"Île-du-Prince-Édouard"
    "QC"=>"Québec"
    "SK"=>"Saskatchewan"
    "YT"=>"Yukon");

Categories: PHP Arrays Tags: , , ,

PHP Array Of USA States

April 23rd, 2009 No comments

Use the following array if you want to print out a list of USA states either as a list, or as a select box.

$state_list = array('AL'=>"Alabama",  
    'AK'=>"Alaska",  
    'AZ'=>"Arizona",  
    'AR'=>"Arkansas",  
    'CA'=>"California",  
    'CO'=>"Colorado",  
    'CT'=>"Connecticut",  
    'DE'=>"Delaware",  
    'DC'=>"District Of Columbia",  
    'FL'=>"Florida",  
    'GA'=>"Georgia",  
    'HI'=>"Hawaii",  
    'ID'=>"Idaho",  
    'IL'=>"Illinois",  
    'IN'=>"Indiana",  
    'IA'=>"Iowa",  
    'KS'=>"Kansas",  
    'KY'=>"Kentucky",  
    'LA'=>"Louisiana",  
    'ME'=>"Maine",  
    'MD'=>"Maryland",  
    'MA'=>"Massachusetts",  
    'MI'=>"Michigan",  
    'MN'=>"Minnesota",  
    'MS'=>"Mississippi",  
    'MO'=>"Missouri",  
    'MT'=>"Montana",
    'NE'=>"Nebraska",
    'NV'=>"Nevada",
    'NH'=>"New Hampshire",
    'NJ'=>"New Jersey",
    'NM'=>"New Mexico",
    'NY'=>"New York",
    'NC'=>"North Carolina",
    'ND'=>"North Dakota",
    'OH'=>"Ohio",  
    'OK'=>"Oklahoma",  
    'OR'=>"Oregon",  
    'PA'=>"Pennsylvania",  
    'RI'=>"Rhode Island",  
    'SC'=>"South Carolina",  
    'SD'=>"South Dakota",
    'TN'=>"Tennessee",  
    'TX'=>"Texas",  
    'UT'=>"Utah",  
    'VT'=>"Vermont",  
    'VA'=>"Virginia",  
    'WA'=>"Washington",  
    'WV'=>"West Virginia",  
    'WI'=>"Wisconsin",  
    'WY'=>"Wyoming");

If you want to reverse this then use the following code.

$reverse = array();
foreach ( $state_list as $key=>$state ) {
    $reverse[$state] = $key;
}
$state_list = $reverse;

Categories: PHP Arrays Tags: , , ,

Reading And Writing To Compressed gzip Files

April 23rd, 2009 No comments

Reading and writing to compressed gzip files can be done in much the same way as reading and writing normal files. The main difference is the use of some special functions that compress and uncompress the data. Rather then use fopen() to open a file, you open a compressed file with gzopen(). This is the case for many of the file access functions, although you should be aware that they don’t all work exactly the same as each other. Here are some examples of the compression functions in use.

To read from a compressed file use the following script.

// read from file
$inputfile = 'text.gz';
 
$filecontents = '';
 
$ifh = gzopen($inputfile, 'r');
 
while ( $line = gzgets($ifh, 1024) ) {
    $filecontents .= $line;
}
echo $filecontents;
gzclose($ifh);

To write to a compressed file use the following script.

// writing to a complessed file
$inputfile = 'text.gz';
 
$string = 'lalalala';
$filecontents = '';
 
$ifh = gzopen($inputfile, 'r');
 
while ( $line = gzgets($ifh, 1024) ) {
    $filecontents .= $line;
}
gzclose($ifh);
 
$ifh = gzopen($inputfile, 'w');
if ( !gzwrite($ifh, $filecontents.$string) ) {
    // write failed
}
 
gzclose($ifh);
 

To compress a normal file use the following script.

// compress
$inputfile = 'text.txt';
$outputfile = 'text.gz';
 
// open files
$ifh = fopen($inputfile, 'rb');
$ofh =  fopen($outputfile, 'wb');
 
// encode string
$encoded = gzencode(fread($ifh, filesize($inputfile)));
 
if ( !fwrite($ofh, $encoded) ) {
    // write failed
}
 
// close files
fclose($ifh);
fclose($ofh);

To uncompress a gzip file use the following script.

// uncompress
$inputfile = 'text.gz';
$outputfile = 'text.txt';
 
$ofh =  fopen($outputfile, 'wb');
 
$string = '';
 
$ifh = gzopen($inputfile, 'r');
while ( $line = gzgets($ifh, 1024) ) {
    $string .= $line;
}
 
if ( !fwrite($ofh, $string) ) {
    // write failed
}
 
echo $string;
 
gzclose($ifh);
fclose($ofh);

Notice from these examples that you can open a compressed file using fopen(), but you need to use the 'b' flag to indicate to fopen that you want the file to be opened in a binary format. Basically, the two following calls are very much the same.

$ifh = gzopen($inputfile, 'r');
$ifh = fopen($inputfile, 'rb');

The gzopen() function can also take some other parameters as the mode. These include the compression level (eg. wb1 or wb9) or a strategy. The strategy can be either f for filtered (used as wb9f) or h for Huffman only compression (used as wb1h).

Categories: PHP Tags: , , , , , , ,

Ping A Website Using PEAR’s Net_Ping

April 22nd, 2009 No comments

Net_Ping is a PHP wrapper for the ping program and provides a neat way pinging a host or checking if a site is up and running. To install it you just need to have pear installed. Once that is done you can do a search for PEAR Net_Ping by opening a terminal and typing:

>ping search ping

This will return the following:

Retrieving data...0%.MATCHED PACKAGES, CHANNEL PEAR.PHP.NET:
=======================================
PACKAGE           STABLE/(LATEST) LOCAL
Net_Ping          2.4.4 (stable)        Execute ping
Services_Pingback 0.2.2 (alpha)         A Pingback User-Agent class.

You can install Net_Ping by running the following:

H:>pear install Net_Ping

Which should produce the following output.

downloading Net_Ping-2.4.4.tgz ...
Starting to download Net_Ping-2.4.4.tgz (9,563 bytes)
.....done: 9,563 bytes
install ok: channel://pear.php.net/Net_Ping-2.4.4

You can now use Net_Ping. To use the class in your code you need to include it first, after this you need to get an instance of the Net_Ping object so that you can work with it. The following code will create a Net_Ping object that you can work with.

require_once "Net/Ping.php";
$ping = Net_Ping::factory();

To ping a site you just need to run the ping() function. This function takes a single parameter which is the IP address or the name of the server you want to ping. The function returns a Net_Ping_Result object that contains all of the information returned from the ping.

$results = $ping->ping('www.example.com');

Here is a print_r() output of this object.

Net_Ping_Result Object
(
    [_icmp_sequence] => Array
        (
            [1] => 176
            [2] => 177
        )
 
    [_target_ip] => 208.77.188.166
    [_bytes_per_request] => 32
    [_bytes_total] => 64
    [_ttl] => 54
    [_raw_data] => Array
        (
            [0] => 
            [1] => Pinging www.example.com [208.77.188.166] with 32 bytes of data:
            [2] => 
            [3] => Reply from 208.77.188.166: bytes=32 time=176ms TTL=54
            [4] => Reply from 208.77.188.166: bytes=32 time=177ms TTL=54
            [5] => 
            [6] => Ping statistics for 208.77.188.166:
            [7] =>     Packets: Sent = 2, Received = 2, Lost = 0 (0% loss),
            [8] => Approximate round trip times in milli-seconds:
            [9] =>     Minimum = 176ms, Maximum = 177ms, Average = 176ms
        )
 
    [_sysname] => windows
    [_round_trip] => Array
        (
            [min] => 176
            [max] => 177
            [avg] => 176
        )
 
    [_transmitted] => 2
    [_received] => 2
    [_loss] => 0
)

You can access the different properties within the Net_Ping_Result to find out what happened with the ping. The percentage of pings lost is also worked out for you in the _loss property.

echo '<p>Transmitted: '.$results->_transmitted.'</p>';
echo '<p>Received: '.$results->_received.'</p>';
echo '<p>% Loss: '.$results->_loss.'%</p>';

The _round_trip parameter contains an array that details the minimum, maximum and average times for the requests.

You might have noticed in my original example that I only sent out 2 pings. This is because the Net_Ping object has a function that allows you to set certain options before you make the request. This function is called setArgs() and takes an associative array as the argument. To set the number of ping requests to be sent out just use the following line of code before you make your ping request.

$ping->setArgs(array('count' => 2));

You should be aware that different operating systems have different options, so for a full list of options please see the Net_Ping::setArgs() page on the PEAR website.

If you just want to check the host to make sure it is still active you can use the checkhost() function. This works in the same way as the ping() function, but will return true on success and false on failure. You can see the output of checkhost() by viewing the var_dump() output.

var_dump($ping->checkhost('example.com'));

This function is really a wrapper for the ping() function, but will parse the output to determine if the ping request worked or not.

Categories: PHP Tags: , , , , ,

Convert A String To A Date Value In MySQL

April 21st, 2009 No comments

There are numerous ways to print out dates and times, and many hours of programming are spent in converting dates from one format to another.

To do this in MySQL you use the STR_TO_DATE() function, which has two parameters. The first parameter is the time to be parsed and the second is the format of that time. Here is a simple example that converts one date format to a MySQL formatted date string.

SELECT STR_TO_DATE('[21/Apr/2009:07:14:50 +0100]', '[%d/%b/%Y:%H:%i:%S +0100]');

This outputs 2009-04-21 07:14:50.

Using this function is quite intuitive and means that you can convert between time formats very easily. Here are a few more examples of this function.

SELECT STR_TO_DATE('21/04/2009', '%d/%m/%Y'); // 2009-04-21
SELECT STR_TO_DATE('04/21/2009', '%m/%d/%Y'); // 2009-04-21
SELECT STR_TO_DATE('2009-04-21 14', '%Y-%m-%d %H'); // 2009-04-21 14:00:00

If you enter a date that can’t be translated then you will get an error, take the following code that tries to convert a minute value of 87.

SELECT STR_TO_DATE('2009-04-21 14:87', '%Y-%m-%d %H:%i');

The following error message is returned.

Incorrect datetime value: '2009-04-21 14:87' for function str_to_date

This error can be quite easy to reproduce. For example, if you wanted to parse a time that was in 24 format, you would use the %H for hours. Using the %h value for hours will produce exactly this error.

The following table lists all of the different parameters that are involved in the date formatting features within MySQL. Use this to parse your own dates.

Specifier Description
%a Abbreviated weekday name (Sun..Sat)
%b Abbreviated month name (Jan..Dec)
%c Month, numeric (0..12)
%D Day of the month with English suffix (0th, 1st, 2nd, 3rd, …)
%d Day of the month, numeric (00..31)
%e Day of the month, numeric (0..31)
%f Microseconds (000000..999999)
%H Hour (00..23)
%h Hour (01..12)
%I Hour (01..12)
%i Minutes, numeric (00..59)
%j Day of year (001..366)
%k Hour (0..23)
%l Hour (1..12)
%M Month name (January..December)
%m Month, numeric (00..12)
%p AM or PM
%r Time, 12-hour (hh:mm:ss followed by AM or PM)
%S Seconds (00..59)
%s Seconds (00..59)
%T Time, 24-hour (hh:mm:ss)
%U Week (00..53), where Sunday is the first day of the week
%u Week (00..53), where Monday is the first day of the week
%V Week (01..53), where Sunday is the first day of the week; used with %X
%v Week (01..53), where Monday is the first day of the week; used with %x
%W Weekday name (Sunday..Saturday)
%w Day of the week (0=Sunday..6=Saturday)
%X Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V
%x Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v
%Y Year, numeric, four digits
%y Year, numeric (two digits)
%% A literal % character
%x x, for any x not listed above
Categories: MySQL Tags: , , , , , , ,