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

Jun 4 2009

Make Web Sites Think that PHP CURL is a Browser.

I’ve been doing a bit of site scraping using curl and PHP lately. I’ve found that most sites will ban your ip if they think you’re a bot (good thing I’m on DSL) so you need to make them think that your script is a browser. The easiest way to do this is to add a user agent header to your script. Here is an example of getting a results page from google for a specific search query.


function get_google_result($search_term)
{
  $ch = curl_init();
  $url = 'http://www.google.ca/search?hl=en&safe=off&q='
                  .urlencode($search_term);
  $useragent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1)".
                            " Gecko/20061204 Firefox/2.0.0.1";
  
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_HEADER, 1);
  curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  
  $google_string = curl_exec($ch);
  
  curl_close($ch);
  $google_string = utf8_encode($google_string);
  return $google_string;
}

So this function will take the search term that was provided and request the results from google for it. Our user agent header makes the script look like firefox.
I put the returned string (The entire google results page) into the google_string variable and return it for parsing out what is needed. My newest scrape experiment is a site called Quick Content and basically scrapes some results from google based on some parameters from google hot trends and posts it all as a feed. It was fun to code up but it is desperate need of a makeover.

Share

May 27 2009

New PHP 5.3 Release June

Q2 is basically April, May, and June and the 5.3 timeline says Q2 stable release. I’ve been reading mostly good things about the experimental release and considering all the new features being added every php developer should be stoked. I’m not just talking about the new closures/lambda functions which are gonna make my life a lot more fun. Here’s a list of all the fun stuff that I’ll be playing with next month:

  • Namespace support. It’s about time.
  • Late static binding. Somewhere between static and dynamic binding.
  • Jump label (limited goto)
  • Native closures. Simple javascript-like lambda functions. None of that create_function stuff anymore.
  • PHP archives (phar). Not sure why?
  • Garbage collection for circular references.
  • Ternary shortcut. Still haven’t seen an example of what this is?
  • Internationalization extension.

I’ve always been told that goto’s are bad programming practice but sometimes they can be very, very useful. Hopefully they get all the bugs out in the experimental versions and I can start using it at work  shortly after release.

Share

May 26 2009

Anonymous (Lambda) Functions in PHP.

I’ve recently been playing with anonymous (lambda) functions in javascript and I was thinking that it would be great if I could do the same thing in php, which is what I spend most of my time with. Turns out that you can. It’s not as clean and pretty as with javascript but it’s still a lambda function and functional programmers are better…aren’t they?

First the spec :
string create_function ( string $args , string $code )

So here’s a little example of something completely useless that can be done using anonymous functions in PHP :

$first_arg = 100;
$some_function = create_function(‘$first_arg’,’return $first_arg/5;’);

function process($arg,$func)
{
    while($func($arg)>5)
    {
        $arg–;
    }
    return $arg;
}

echo process($first_arg,$some_function);

So we get 25 echoed to the screen. A bunch of better examples can be found at the php website. If you’re willing to read…

Nothing really special but It’s still cool that can pass functions into another PHP function just like a regular variable.


Share