Category Archives: PHP

The Shoulders of Tall, Smart People

Recently, I came to the realization that I’ve been writing computer programs in one form or another since I was about 6 or 7 years old.

Along the way, I’ve had plenty of people to influence the way I think about code, and how I write it.  Sure, there have been plenty of textbooks along the way too, but I want to give some thanks to the people who have directly affected my abilities to do what I do.

And what better way of doing that then by listing them?

A Chronological List of People Who Have Influenced My Coding

  1. My parents, for bringing home our first family computer.  It was an 8088XT IBM Clone – no hard drive, 640K of RAM, dual 5 1/4 floppies…it was awesome.  This is the computer I started coding on – but I couldn’t have started without…
  2. My Uncle Mark and my Aunt Soo.  Both have degrees in Computer Science from the University of Waterloo (that’s where they met).  My recollection is pretty vague, but I’m pretty sure that a lot of the programming texts in my house (a big blue QuickBasic manual comes to mind) surely didn’t come from my parents – must have been those two.  With the book in one hand, and the 8088 in the other, I cranked out stupid little programs, little text adventure games, quizzes, etc.
  3. The online QB community from the late 1990’s to the early 2000’s.  When my family got online, I soon found myself hanging out at NeoZones, in the #quickbasic IRC channel on EFNet… actually, a lot of crazy stuff was being done with QuickBasic back then – I remember when DirectQB came out, and somebody was able to code a raytracer…in BASIC.  It was awesome.  I’d say these were my foundation years, when I learned all of my programming fundamentals.
  4. My friends Nick Braun, Joel Beck, and Doug McQuiggan – these three guys and I used to come up with crazy ideas for games, and I’d try to program them.  I’d come home from school, and pound out code for a computer game for a few hours in the basement.  More often then not, these projects would simply be abandoned, but still, a lot was learned here.
    Joel, Doug, our friend Julian and myself were also members of a band in highschool.  It was my job to build and maintain the band website, and this is when I learned to write HTML, basic Perl, and simple JavaScript.
  5. After highschool, I went into Electrical and Computer Engineering at the University of Toronto.  I didn’t do too well at the Electrical bits, but I could handle myself at the Computer bits.  I learned OOP, Java, and basic design patterns from Prof. James McLean.
  6. I also learned a great deal from Prof. McLean’s course text – Introduction to Computer Science Using Java by Prof. John Carter.  I know I said I wasn’t going to mention textbooks, but I also got taught Discrete Mathematics from Prof. Carter, so I thought I’d toss him in too.
  7. My second (and last) semester in ECE had me taking Programming Fundamentals with Prof. Tarak Abdelrahman.  I learned basic C++ from Prof. Abdelrahman, and how to deal with large systems of code.
  8. After my move to the Arts & Science Faculty, I took my first Computer Science course with Dr. Jim Clarke. I learned about Unit Testing, and more design patterns.  I also eventually learned some basic Python from him, but I think it was in another course.
  9. I took CSC258 with Prof. Eric Hehner, and learned about the structure of computer processors.  Physically, this was a low-level as I’d ever gotten to computers.  I was familiar with writing Assembly from my QB days, but Prof. Hehner’s Opcode exercises were really quite challenging – in a pleasant way.  Also, check out his concept of Quote Notation
  10. After that year, I spent the first of three summers working for the District School Board of Niagara.  Ken Pidgen was my manager, Mila Shostak was my supervisor.  Ken gave me incredible freedom to work, and soon I was developing web applications, as opposed to just fixing up department websites (as I originally thought I would be doing).  Mila gave me guidance, and showed me how to use CSS to style a website.  She also got me started using PHP and MySQL to create basic web applications.
  11. While working at the Board, I had the pleasure of sitting across from Jong Lee.  Jong and I would bounce ideas off of one another when we’d get stuck on a programming problem.  He was very experienced, and I learned lots of practical programming techniques from him.
  12. Michael Langlois and Ken Redekop acted as my clients at the Board, and always gave me interesting jobs and challenges to perform.Everyone at the Board was always very positive with me, and I’ll always be grateful that they took a newbie undergrad under their wing!  I was given a ridiculous amount of freedom at the Board, and was allowed to experiment with various technologies to get the job done.  Through my three summers there, I learned bits about Rails, CakePHP, MVC, network security, how to deploy an application remotely, how to run a local server, how to develop locally and post to remote, ORM, Flash, web security…so many things.  The list is huge.
  13. Karen Reid and Greg Wilson have been the latest influences on me.  The MarkUs Project was the first project I’ve ever worked on with a team.  It was my first time seriously using version control, my first time using a project management portal (Dr. Project), my first time learning Ruby, and my first time working on an open source project.  I’ve also learned plenty about time management, people, the business of software, and how to get things done.  Again, I’ve been given lots of freedom to learn, experiment, and hone my craft.

Anyhow, these are the people who come to mind.  I might add to this list if I remember anyone else.

But in the mean time, for the people listed above:  thank you.

My Web App in the News

ANOTHER UPDATE: Whoops.  Fixed the links to the auction and the St. Catharines Standard article.

UPDATE: Apparently, the Feds are getting in on the online auction circuit too.

Over the past three summers, I’ve been employed by the District School Board of Niagara as an internal web application developer.

One of my first jobs in the summer of 2006 was to rebuild the online auction application that the DSBN Purchasing department ran.  The original auction let the Board dispose of old equipment quickly and easily, and was quite popular.  Unfortunately, it was also written in (almost) unintelligible/unmaintainable Perl.

So I rewrote it by myself, and learned PHP/MSSQL along the way.  We called this new auction site The Government Surplus Online Auction, and we opened it up so that other government agencies could also post items for auction.

Things went along fine until last summer, when the site got attacked by an SQL Injection bot.  Back in 2006, I had no idea what SQL injection was, or how to guard myself.

So there I am – I’ve just come back from a camping trip, my inbox is packed with complaints, and I’ve got three weeks until school begins.  Crap.

Luckily, I had plenty of tools at my disposal.  My web app development skills and practices had evolved dramatically since 2006, and I had been itching to reimplement the auction anyhow.  The SQL Injection attack was a perfect excuse for me to gut the entire application, and rebuild from scratch.

And I did.  I rebuilt the whole thing from the ground up in three weeks.  It’s been almost a year since it was deployed, and I’m still very happy with its performance, and the code that runs it.

I’m not happy with its overall UI design.  I think there are plenty of improvements to be made in that regard.  Luckily, it’s coded using a light MVC framework that I designed/built myself, so reskinning shouldn’t be too hard for whoever decides to work on it…

Apparently, I’m not the only one happy with the auction site.  Check out this article (now without annoying print dialog).

I just checked the logs today – we hit a new record: an aerial truck went for $22,000 dollars.  With the Board receiving 5% ($1100) of that simply for hosting, I think everybody is walking away happy.

Here’s the auction.

Proof that I wrote it?  This’ll have to do.

SQL Injection Prevention in PHP – Tip 1

It’s amazing – I’ve been going around, Googling for anything with “index.php?id=”…and that’s really all it takes.  Now, granted, SQL Injection isn’t new, and a lot of the top hits have taken some steps to protect themselves, but if you go deep – like, Google search page 23 deep – you’ll find ones that break if you put a semi-colon after the id # – and if it breaks, it’s vulnerable.

So, here’s my first tip on preventing SQL Injection – when you’re asking for an ID number, make sure it’s a number, and nothing else. Also consider using prepared statements – database wrappers like MDB2 for PHP make this easy.

Check this out – this might be how I would have done it 3 years ago:

<?php
  //Assume we're already connected to a MySQL database...
  $id = $_GET['id'];

  $result = mysql_query('SELECT * from pages where id='.$id);
  if (!$result) {
     die('Invalid query: ' . mysql_error());
  }
  ... //Code to print out my result to the page
?>

I’d do it this way now:

Note: My use of MDB2 might be a little rusty – I haven’t tested this code, and I usually compose RowDataGateway objects with MDB2 to represent my data.  So pay more attention to the structure than the actual syntax.

<?php
  require 'View.php';
  require 'MDB2.php';  //An excellent DB layer from the PEAR libs

  //Code to set $mdb2 as our DB connection variable
  //See http://pear.php.net/package/MDB2 for details
  $id = $_GET['id'];

  try {
    if(!is_int($id)) {
      //ID wasn't an int, it's no good, let's bail
      throw new Exception('Could not recognize the id that you passed');
    }
    //ID was an int, let's see if we can find the record
    $sql = 'SELECT * from pages where id=:id";
    $statement = $mdb2->prepare($sql);
    $statement->bindParam('id', $id);
    $result = $statement->execute();
    if(PEAR::isError($result)) {
      //Uh oh - our result was an error on the PEAR library level
      throw new Exception('There was an error communicating with the database');
    }
    //Insert the database result into the view, render, and die.
    $content = new View('templates/page.tpl', array('page' => $result->fetchOne()));
    $content->render();
    die;
  }
  catch(Exception $e) {
    //We must have caught an exception - put this into our
    //error page template with the error message, render, die.
    $content = new View('templates/error.tpl', array('message' => $e->getMessage()));
    $content->render();
    die;
  }
?>

Yes, it’s quite a bit more code. But I feel safer just looking at it.
Did I miss anything on this? Please post a comment if you  notice that I’ve left a gaping hole.  Learning is good.

Preventing SQL Injection Attacks

Over the reading week, along with studying for various midterms and assignments, I’ve decided to brush up on preventing SQL Injection attacks in web applications.

Pretty scary/awesome stuff out there on this stuff.  Here’s a great place to get some SQL Injection training, and here’s an excellent SQL Injection cheat sheet.

I got hit with a pretty bad SQL Injection attack last summer on an application I had written 3 years ago (before I had any clue that SQL Injection attacks were possible).

Here’s the take home message:  never trust user input.  Ever. If you’re expecting an int, make sure it’s an int.  Never insert user input directly into an SQL string. Use prepared statements instead, or stored procedures.

Luckily, I just did a quick survey of all of my running apps, and I seem to be OK in terms of SQL Injection.  Still, it’s a common attack vector – and the consequences of being lazy on user input can be pretty awful.

Update: Want to see something awesome?  Check this out – a Debian box gets rooted through MySQL injection…killer soundtrack too.

Model-View-Controller in PHP: Model

(Notes:

)

I have one thing to say for all of those PHP developers who look at Rails’ ActiveRecord class and get all excited about implementing it in PHP:

It can’t be done.  Yet.

Here’s why:

Until PHP5.3, PHP does not implement a feature called “late static binding”.  What is late static binding?  Well, how about I show you what it’s like to NOT have late static binding:

class A {
   public static function who() {
     echo __CLASS__;
   }
   public static function test() {
     self::who();
  }
}
class B extends A {
  public static function who() {
    echo __CLASS__;
  }
}
B::test();  //Outputs:  'A'

That’s right:  B::test() outputs ‘A’.  This is a problem, because while it is true that B is a subclass of A, B is still B.  When I call a static method of B, I want it to know that it’s B.

With late static binding (only available in PHp5.3 and onward), this goes away:

<?php
class A {
  public static function who() {
    echo __CLASS__;
  }
  public static function test() {
    static::who(); // Here comes Late Static Bindings
  }
}
class B extends A {
  public static function who() {
    echo __CLASS__;
  }
}
B::test();  //Outputs 'B'
?>

Why is this a problem for ActiveRecord?  Well, say we define a class called ActiveRecord, and create a subclass of ActiveRecord called Person.  When I call Person::find_all(), PHP5.2 is going to run find_all in ActiveRecord – and ActiveRecord’s find_all() will not know what kind of subclass I am.  It won’t know if I’m a Person, Dog, Pizza, or any of that jazz.  Essentially, ActiveRecord is now dead in the water.

Now, you could just make find_all a standard method instead of a static one, but then for every find operation, you’d have to do this:

$p = new Person();
$persons = $p->find_all();

Semantically, this doesn’t make much sense.

But, PHP coders, take heart –  there are two silver linings: