Jun 20 2009

Canadian ISP’s Soon To Be Logging And Sharing

Last week the Public Safety Minister, Peter Van Loan, introduced a bill that could force ISP’s to allow police access to all our network data without a warrant. If this were to pass then all the internet service providers would save all our private data and give it up anytime the cops want to have a look at it. This seems to be pretty common practice in many other countries but I was always proud to live in a place where your every action isn’t logged and processed.

Read More

http://www.publicsafety.gc.ca/media/nr/2009/nr20090618-eng.aspx?rss=true


http://www.michaelgeist.ca/content/view/4069/125/

Share

Jun 20 2009

Get Integer Bit Parity In PHP

I was forced to use php to generate a cyclic redundancy check (CRC) byte earlier this week. When generating this CRC I needed to check the bit parity of a byte. At first I thought that there would be an example that I could just cut and paste into my code or a library including the function somewhere. I guess that most PHP users don’t really have to work with bits and bytes very often because I couldn’t find an example of doing this. Granted I didn’t really search that hard because writing it was pretty simple. But hopefully the next guy searching for this actually finds this example.

Most of the time we don’t really have to think about types in php. But if you’re dealing with this kind of thing then you usually want to know what you’re working with. This php function example will only work with integers and will return a value of -1 if the first parameter is not a number. The function returns 1 if the number of bits set in the number pased in is odd. Otherwise it will return 0. The second parameter defaults to 4 because that is the number of bytes in a normal php integer. In php if a number becomes larger than an integer can handle, which is called an overflow, it becomes a float. The default integer size is platform dependant but it’s usually 4 bytes. It can be set using the constant PHP_INT_SIZE if you need to change it.


<?php

function odd_parity($something,$number_of_bytes_to_check=4,$double_check=0)
{
    //test to make sure it's a number
    if(!is_numeric($something)) {return -1;}  

    $setbits = 0;

    //get the number of bits that are set
    for($i=0;$i<$number_of_bytes_to_check*8;$i++)
    {
        if($something & (1<<$i)) $setbits++;
    }

    //check if the number of bits set is even or odd   
    $result =  $setbits % 2;
   
    //spit out the results to double check it's working 
    if($double_check)
    echo   "<br>Parity of : ".$something." is ".
    $result." In Binary : ".decbin((int)$something).
    " Checking the right ".($number_of_bytes_to_check*8).
    " Bits";

    return $result;
}

//will return 0 because it's defaulting to 4 bytes
echo odd_parity(0x0100010001);  

?>

Share

Jun 17 2009

Generate A Tiny URL On The Fly With PHP

Uniform resource locators (URL) are starting to get very long and I’m getting sick of typing ridiculously long strings into safari on my iphone. I don’t really care about the extra bandwidth, It’s just annoying when you’re on the phone telling someone to go check out a 67 character long url and they mistype it three times.

I’ve just started using the tiny url service and so far it’s been useful. On one of my sites I wanted to generate a tiny url for each of my pages to make them quicker to type in and also so people don’t know what get variables I’ve set until they get there. Here is the PHP function that I used to generate a tiny url for every page on the site.

There doesn’t seem to be any documentation at all on the Tiny URL website about this so I’m not sure if it’ll change in the future.
This function passes your desired url to the api-create.php script on the tinyurl domain which returns a nice short url that isn’t a pain to put into your iphone.


function get_tiny_url($url)
{
  $new_url = file_get_contents('http://tinyurl.com/api-create.php?url='.$url);
  return $new_url;
}

$tiny_url = get_tiny_url("http://codytaylor.org");

Not much to it but it made my life easier.

Share

Jun 15 2009

Apparently IT Workers Have Loads Of Free Time

IT Workers Have Lots Of Spare Time

IT Workers Have Lots Of Spare Time

Share

Jun 15 2009

Checking Bits With PHP

PHP makes life a lot easier for quick or dirty maintenance scripts, cron jobs or web applications but how does it do for older, not so straight forward problems dealing with bits and bytes? I was surprised how easy it was to manipulate bits in a byte with php. Here is an function that made my life a fair amount easier when having to check for a specific bit in a byte.

This function checks whether a certain bit is set or not given a byte and an index. It returns true if the chosen bit is set. It casts the $value argument to a integer just in case. The index $n goes from left to right so the most significant bit is bit one and the least significant is bit eight. This function will only work for integers between 0 and 255 because that was all I needed at the time. It would be trivial to write either a function to separate bytes in an integer or to increase the amount of bits that this function checks. I originally had a different function here but the Internet quickly told me that there was an easier way to do this.


<?php

function check_bit($value,$n=8)
{
    $value = (int)$value;
    if($value & (1<<(8-$n))) { return true; }
    else { return false; }
}

//Check Bit Usage Example
$test_byte1 = "4";

if( check_bit($test_byte1,2))
  echo "Bit 2 is set in ".decbin($test_byte1);
else
  echo "Bit 2 is not set in ".decbin($test_byte1);

?>

Here are the php bitwise operator definitions from the php documentation. Look like C much?

$a & $b And Bits that are set in both $a and $b are set.
$a | $b Or Bits that are set in either $a or $b are set.
$a ^ $b Xor Bits that are set in $a or $b but not both are set.
~ $a Not Bits that are set in $a are not set, and vice versa.
$a << $b Shift left Shift the bits of $a $b steps to the left (each step means “multiply by two”)
$a >> $b Shift right Shift the bits of $a $b steps to the right (each step means “divide by two”)
Share

Jun 14 2009

Detect Bots By Parsing The User Agent With PHP

Because I’ve been starting to keep a closer eye on my traffic I’ve been logging everything to my databases. When writing reports for this information I noticed that there was huge amounts of traffic from bots. Yahoo, Google, MSN and many others have been hammering my sites quite a lot lately. Since I’m writing my reports in PHP I needed a quick little function to identify whether the visitor was real traffic or some machine scraping my site. I couldn’t find one after a few quick Google queries but the solution was trivial so I wrote my own. Hopefully this will save someone a few minutes. The function is as simple as possible and it seems to be working so far. I’ve been watching it for awhile and it hasn’t missed any yet. I’m assuming that it’s not going to catch everything but it would be nice to get most. Any bot user agent string suggestions would be helpful.


//returns 1 if the user agent is a bot
function is_bot($user_agent)
{
  //if no user agent is supplied then assume it's a bot
  if($user_agent == "")
    return 1;

  //array of bot strings to check for
  $bot_strings = Array(  "google",     "bot",
            "yahoo",     "spider",
            "archiver",   "curl",
            "python",     "nambu",
            "twitt",     "perl",
            "sphere",     "PEAR",
            "java",     "wordpress",
            "radian",     "crawl",
            "yandex",     "eventbox",
            "monitor",   "mechanize",
            "facebookexternal"
          );
  foreach($bot_strings as $bot)
  {
    if(strpos($user_agent,$bot) !== false)
    { return 1; }
  }
  
  return 0;
}

Share

Jun 10 2009

Match An IP Address To A Physical Location With PHP

Sometimes it’s useful to locate where a certain IP address is located. Usually this isn’t really that accurate but at least it gives you a general idea for stats or marketing research. I’ve written a simple php function that uses curl to query a IP address location database for the location info. In the function I specify that I want a JSON data structure containing the location information. I chose JSON over the XML alternative just for ease of use. The object that we get returned needs to be referenced in a specific kind of way. I show how under the function.
This function uses the IPInfoDB JSON php API. There are quite a few alternatives out there so feel free to do your research. The IPInfoDB PHP API returns :

  • Country Code (CA or US)
  • Country Name (Canada)
  • Region Code
  • Region Name (Province or Dtate)
  • City
  • Postalcode or Zip Code (which doesn’t always work)
  • Latitude
  • Longitude
  • gmt offset
  • Dst offset


function get_location_info($ip_address)
{
  $url = 'http://ipinfodb.com/ip_query.php?ip=';
  $url .= $ip_address;
        $url .= '&output=json';
  $ch = curl_init();
  
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
  $json_packet = curl_exec($ch);
  $location_array = json_decode($json_packet);
  curl_close($ch);
  return($location_array);

}//get_location_info

$loc_arr = get_location_info("69.157.107.64");
echo "\n";
echo $loc_arr->{'City'};
echo "\n";
echo $loc_arr->{'RegionName'};
echo "\n";
echo $loc_arr->{'CountryCode'};

Hopefully theres no confusion there.

Share

Jun 9 2009

Adding Sack Ajax To Your WordPress Plugin’s Admin Page

Using my previous wordpress example plugin I’m going to demonstrate how to use ajax within the admin panel. WordPress uses the Simple AJAX Code-Kit (SACK) which is relatively easy to use and understand.

For this example I’m going to expand on my previous example and add a simple javascript function that queries some data from the server. WordPress forces us to do this in a roundabout way. First we have to add two new function hooks. One prints my javascript function in the scripts section of the admin panel and the other is the code that gets called by the ajax sack request.


//add my custom ajax function to the scripts section in the admin panel
add_action('admin_print_scripts', 'ajax_request');

//add data returning ajax refresh table function
add_action('wp_ajax_do_something', 'get_random_number');

The ajax_request function is a shell function for the javascript ajax call get_random_number_from_server which is our sack ajax request. Note that we are calling the admin-ajax.php script. This script will handle the calling of the get_random_number function for us because of the action defined above.


//This function will print out in the header section. 
//Put all your javascript in this function.
function ajax_request()
{
        //print out the sack ajax library
        wp_print_scripts( array( 'sack' ));  
  ?>
  <script type="text/javascript">
  //<![CDATA[
    
  function get_random_number_from_server()
  {
    //creates the sack object and 
                //gives it the url that it should request to.
    var mysack = new sack( '<?php 
                bloginfo( "wpurl" ); ?>/wp-admin/admin-ajax.php' );    
        
    mysack.execute = 1;   //execute whatever is returned
    mysack.method = 'POST';
    
    //Set POST fields
    mysack.setVar( "action", "do_something" );
        
    mysack.encVar( "cookie", document.cookie, false );
    mysack.onError = function() { alert('Ajax Error')};
    mysack.runAJAX();  //run the result

    return true;

  } // end of JavaScript function myplugin_ajax_elevation
  //]]>
  </script>
  <?php
  
}

This is the php function that is called by the javascript function above. It spits out a alert javascript function and then dies. Not sure why but it is recommended to die in this function.


//This is the server side code for the ajax sack request
function get_random_number()
{
  $minimum_number = 0;
  $maximum_number = 100;
  die("alert('".rand($minimum_number,$maximum_number)."');");
} 

This code can now be run like the following in your plugins admin page.


<input type='button' value='Get Random Number' 
onclick='get_random_number_from_server();'>

When the button is hit a popup with a random number in it will pop up. Here’s a link to the entire example plugin code.

Share

Jun 7 2009

Simple WordPress Example Plugin

I wrote a plugin for wordpress this weekend and all the documentation and guides were fairly long winded. This is probably a good thing for most people but I never like large amounts of reading for something simple. So the following outlines and explains a very short and simple plugin for wordpress.

WordPress uses hooks to give plugins certain places to execute code. Hooks are created by using the add_action function where the first parameter is the desired, predefined hook and the second is the name of the function that you want to be called at that point. Check out the list of hooks.

In this example I first hook the install function which will be run when the plugin is activated. The second hook defines a function that will be called when a page is loaded and the footer code is executed. The third hook is for the admin menu. This one is a bit of a two step hook. For some reason wordpress makes you call a second function on top of the add_action function in order to get an entry in the admin panel. So the add_options_page is used for just that. It creates a page under the settings header called ‘WP Example’. the third parameter is the name of the function that creates the admin options page.

The commented out name and example at the top of the script is actually used by wordpress when you are activating and deactivating the plugin.

Here’s the code:


<?php

/* Plugin Name: Example Plugin
 * Description: Simple Example Plugin
 *  */

//hook the installation function to the activation plugin
register_activation_hook(__FILE__,'install_example');

//run the alert_user function in the wp_footer 
add_action( 'wp_footer', 'alert_user', 20);

//create a admin page 
add_action('admin_menu', 'my_example_admin_menu');

//make the example_options function is the admin option page
function my_example_admin_menu() {
  add_options_page(  'WP Example Options', 
            'WP Example', 
            8, 
            __FILE__, 
            'example_options');
}

//This code is run on the admin options page for this plugin
function example_options() {
    echo "<div>This Simple Example Plugin Welcomes Every Visitor</div>";
}

//This funtion is called in the wp_footer and welcomes every visitor
function alert_user()
{
    echo "<script type='text/javascript'>".
                  "alert('Welcome to My Wordpress Blog');".
                  "</script>";
}

//This function is run when we activate the plugin
//It is where we would put all our create table and option code
//Since this is a simple example we won't do anything here
function install_example() 
{
     

}
?>

If you put all that in a .php file and upload it to your wp-content/plugins directory you can activate it, deactivate it, view the options page and it will alert every user that comes to your site.

Share

Jun 6 2009

Get Site Visitor Information With PHP

I wanted to do a few custom things with one of my site’s stats. PHP made this nice and simple with the $_SERVER array. When someone visits one of your scripts the $_SERVER array is automatically filled so as long as you know the keys then you can get all the information needed. These are the most useful items for identifying a visitor that I found in this using this array.

$_SERVER[‘REMOTE_ADDR’] gives you their ip address.
$_SERVER[‘HTTP_USER_AGENT’] is their user-agent (What browser they are using).
$_SERVER[‘HTTP_REFERER’] is where they came from.
$_SERVER[‘REQUEST_URI’] is the page they want to view.

This data is kinda useless unless you put it in a database so here’s a create table mySQL statement.


$sql = "CREATE TABLE visitors (
      `visitor_id` mediumint(11) NOT NULL AUTO_INCREMENT,
      `ip_address` VARCHAR(16)  NOT NULL,
      `user_agent` varchar(100) NOT NULL default '',
        `time_of_visit` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      `referrer` varchar(256) NOT NULL default '',
      `target_url` VARCHAR(256) NOT NULL,
      PRIMARY KEY  (`visitor_id`)      
  );";

If you’d like to explore the $_SERVER array more there is very detailed info at the php web site.

Share