Christer’s blog o’ fun

June 28, 2008

Zend_Service_ReCaptcha in the standard incubator

Filed under: PHP, Technology — Tags: , , , , — christer @ 11:24 am

I imported the Zend_Service_ReCaptcha stuff to the Zend Framework standard incubator yesterday. You can access it from the subversion repository at http://framework.zend.com/svn/framework/standard/incubator/library/Zend/Service/.

The component also includes a class to use the mail hide feature over at recaptcha.net that allows you to render an email address as something like user…@foo.com and the reader has to solve a recaptcha to see the complete email address.

No documentation has been made yet but I will include some basic usage of the component in this post.

Display a ReCaptcha in a form

First you need to register at recaptcha.net to get a set of public/private keys for the domain you want to use the recaptcha on. If you develop something locally and you use localhost as hostname you will need to register localhost on the recaptcha site to get the keys. Once you have the keys you are good to go!

When displaying the captcha you will only need the public key. The private key will be used when you verify the user input to see if a user has solved the captcha or not.


<?php
/** @see Zend_Service_ReCaptcha */
require_once 'Zend/Service/ReCaptcha.php';

$publicKey = 'my public key from recaptcha.net';
$reCaptcha = new Zend_Service_ReCaptcha($publicKey);
?>

<html>
    <head>
        <title>ReCaptcha test</title>
    </head>
    <body>
        <form action="" method="post">
            <?= $reCaptcha ?>
            <input type="submit" name="submit" value="Submit" />
        </form>
    </body>
</html>

Replace the public key with your own public key and you will see something that hopefully resembles this screenshot:

Zend_Service_ReCaptcha

Verify the user input

Now that we have our recaptcha in place we need to verify the user input. To do that we have to expand the block of php code at the top of our example here a bit.

PS! The syntax highlight plugin manages to write !emptyempty in the code below, so you’ll need to fix that if you copy the code.


<?php
/** @see Zend_Service_ReCaptcha */
require_once 'Zend/Service/ReCaptcha.php';

$publicKey = 'my public key from recaptcha.net';
$reCaptcha = new Zend_Service_ReCaptcha($publicKey);

// See if the form has been posted and that the two fields from the
// recaptcha are not empty
if (isset($_POST['submit']) &&
    !empty($_POST['recaptcha_challenge_field']) &&
    !empty($_POST['recaptcha_response_field']) ) {
    // Set the private key. We need this to verify user input
    $privateKey = 'my private key';
    $reCaptcha->setPrivateKey($privateKey);

    // See if the input is valid
    $response = $reCaptcha->verify($_POST['recaptcha_challenge_field'],
                                   $_POST['recaptcha_response_field']);

    if (!$response->isValid()) {
        // Not valid. Add the error message from the recaptcha web service
        // to the recaptcha object so it will be shown in the recaptcha
        $reCaptcha->setParam('error', $response->getErrorCode());
    } else {
        // Success! The recaptcha has been solved
    }
}
?>

<html>
    <head>
        <title>ReCaptcha test</title>
    </head>
    <body>
        <form action="" method="post">
            <?= $reCaptcha ?>
            <input type="submit" name="submit" value="Submit" />
        </form>
    </body>
</html>

And thats it!

Hide email addresses with Zend_Service_ReCaptcha_MailHide

If you need to display an email address you can hide parts of it using the Zend_Service_ReCaptcha_MailHide component. You need a separate pair of public/private keys for this so head over to recaptcha.net and grab those keys.

Lets say we want to hide mynewemailaddress@domain.com. Do something like the following piece of code:


/** @see Zend_Service_ReCaptcha */
require_once 'Zend/Service/ReCaptcha/MailHide.php';

$publicKey = 'my public key';
$privateKey = 'my super duper private key';

$mailHide = new Zend_Service_ReCaptcha_MailHide($publicKey,
                                                $privateKey,
                                                'mynewemailaddress@domain.com');

print($mailHide);

The output of this will be myne…@domain.com except that the “…” part will have link to a JavaScript popup that displays a recaptcha, and once the user solves it, the complete email address will be displayed.

So … feel free to play around with the component and if you find some errors or feel that something is missing, let me know! I will add some more stuff about custom themes the next couple of days and maybe make a Zend Framework theme for the recaptcha.

June 25, 2008

Enforcing a PHP coding standard using PHP_CodeSniffer - Part 1

Filed under: PHP, Technology — Tags: , , , , , , — christer @ 9:45 pm

This is the first part of a rather exciting trilogy (a thriller if you may) on how to use the PHP_CodeSniffer component from the PEAR repository to force developers to follow a set of coding standards before allowing them to commit code to a Subversion repository. This can also be accomplished using other Version Control Systems (VCS’s) but I will focus on Subversion. In this part of the trilogy I will explain the importance of having a coding standard, and I will give you a short introduction on how the PHP_CodeSniffer component works and some basic usage of it.

Let’s get on with the show!

When working together with other developers it’s important to agree on some sort of coding standard (not only in PHP). Why is this important you say? You don’t always get to play with stuff you have written yourself. Whenever you are to debug code that someone else wrote, wouldn’t it be great to know that he/she writes code that at least looks like your own?

Using a coding standard doesn’t force developers to solve problems the exact same way, but it might make the solution easier to read for other developers. It might also help developers from doing some pretty nasty errors. Let’s say you have the following piece of code:


if (isset($_COOKIE['userId']) && isset($_COOKIE['userSecret'])) {
    $actualUserSecret = fetchUserSecretCode($_COOKIE['userId']);

    if ($actualUserSecret = $_COOKIE['userSecret']) {
        // ok … the secret code in the cookie is the same as the one
        // returned from the fetchUserSecretCode function. Let's login
        // the user

        // …
    }
}

Now … the code above is all valid, but it contains a pretty nasty bug. The line that says:


if ($actualUserSecret = $_COOKIE['userSecret']) {

is missing an equal sign, so it will always evaluate to true, which in this case will log in the user with the user id from the cookie. If you want to log in as other users you could just change the user id in the cookie, and make a new request, and voila!

This bug is pretty hard to identify since the developer who wrote it probably just didn’t press the equal sign hard enough the second time and the code produced it still valid. The developer “knows” that the error has to be somewhere else and doesn’t even look in the right place. Some of you reading this is probably saying something like: “Come on, nobody will ever manage to do something that stupid!?”. The reason I chose this as an example is because yours truly exploited this “bug” in someone’s code once, so yeah … it’s possible to write something like the example above.

Another issue is when users start to mix up tabs and spaces for indentation and have different editor settings. If you open up a script that has both tabs and spaces used for indentation and your editor has a different tab width than the one who used spaces as indentation all hell breaks loose. Suddenly you won’t even get to order breakfast from your favorite Whammy Burger because you had to spend five extra minutes removing someone’s tabs and, well, we all know what happens next…

What has this got to do with a coding standard? What if the coding standard you were said to follow specified that doing assignments inside an if-test was illegal or that the use of tabs as indentation (or tabs in your code at all) were strictly forbidden? Wouldn’t that fix this issue? That depends on how you deploy the code you are writing. To be able to enforce a standard you need to attach a check that finds out if the code you are sharing with other developers adheres to some standard. Subversion (and other VCS’s) will let you add “hooks” to different events that occur. The event we would like to attach the coding standard check to is the one that occurs before the changes in code actually gets pushed to the repository: the pre-commit event. This event, as it’s name clearly specifies, happens before the commit is done, and it has the power to stop the commit from happening.

The next question is how do we actually check the code against a standard? This is where the PHP_CodeSniffer component comes into play. As its name implies, it will actually sniff PHP code. You might have heard Ramones singing something about wanting to sniff some glue… I’ll let you in on a little secret: The original lyrics actually went a little something like this:

Now I wanna sniff some code
Now I wanna have strings to explode
All the kids wanna sniff some code
All the kids want strings to explode

Let’s get on with the show and start sniffing that code!

PHP_CodeSniffer uses something called sniffs and tokens to pull this off. A Sniff is actually a PHP class that checks one part of the coding standard only. A coding standard in PHP_CodeSniffer is a collection of these sniff classes. One example of a sniff is: “Disallow Tab Indentation”.

A token is an internal representation of a part of userland PHP code. Most of you have probably seen a token in an error message. If you do something like:


$foo = 'foo'
$foobar = $foo . 'bar';

you will get “syntax error, unexpected T_VARIABLE in … ” because you forgot to end the first line with a semi-colon. This actually shows us that some error messages in PHP aren’t all fun and games, but that’s a different story…

The T_VARIABLE part of the error message is as some of you might have guessed a token. PHP_CodeSniffer uses the Tokenizer extension in PHP to generate tokens of the PHP scripts it gets as input and the sniff classes you implement can use these tokens to analyze the input and see if it is correct according to the coding standard.

PHP_CodeSniffer comes with some complete coding standards and enough predefined sniff classes to let you define your own standard by using only predefined sniffs. If you simply want to follow the PEAR coding standard you can use the one that comes with the component. The component also includes a couple of command line scripts (Linux and Windows) that will let you examine your code with little effort.

Since the component belongs to PEAR, the default coding standard is PEAR (no shit Sherlock!). If you also want to use the PEAR standard on your code you can issue the following command (on Linux):

php /path/to/phpcs /path/to/script.php

PHP_CodeSniffer will then analyze script.php and see if it follows the PEAR standard. If not, you will get a bunch of errors informing you on the parts of your code that is different from the standard. If you have lots of code inside a directory you can simply use the name of the directory as argument to the phpcs script instead of the single script name. If you want to use some of the other coding standards that comes with the component you can do so by adding the –standard=<standard> argument. To use the “Zend” standard on a directory of code you can do something like this:

php /path/to/phpcs –standard=Zend /path/to/your/code/

And that’s it for this part actually. In the next part, which I hope to finish sometime this weekend or early next week,  I will create a coding standard in the PHP_CodeSniffer component and show you how to use some of the many sniff classes already defined to get you up and running with a shiny “new” coding standard. I will also show you how to extend some of them to do something a little different.

In the last part I will show you how to implement new sniff classes. The last part will also contain information on how to become the least popular guy on the development team: Add a check to the pre-commit hook so no one can commit code unless it follows the standard 100%!

June 19, 2008

Zend_Service_Recaptcha is accepted

Filed under: PHP, Technology — Tags: , , — christer @ 5:33 pm

Just received a mail from Matthew Weier O’Phinney saying that the Zend_Service_Recaptcha proposal is accepted for inclusion in standard/incubator. So Paddy … you wanna update me on what changes you have done to the initial code soon? :p

May 28, 2008

More Example Zend Framework Blog madness

Filed under: PHP, Technology — Tags: , , — christer @ 9:45 am

May 27, 2008

Chicago - Day 5 (php|tek - Day 3)

Filed under: PHP, Trips — Tags: , , , , — christer @ 12:19 pm

The days are going by pretty fast over here! Suddenly it’s the last day of the conference and soon we will be going back to Norway. Well … these are the talks I attended the last day:

  1. Securing the PHP Environment With PhpSecInfo by Ed Finkler
  2. High Performance PHP & MySQL scaling techniques by Eli White
  3. APC @ Facebook by Brian Shire
  4. The Internet is an Ogre by Terry Chay

The APC talk was pretty much the same as the one I saw at last years php|tek. It included some of the new features of APC but the rest was pretty much the same. Terry Chay’s keynote speech was pretty amusing but contained IMO a bit too many f*ck’s and s*it’s.

After the conference was over we took a short break and headed downtown Chicago for some last day shopping and relaxing. We took a taxi but the driver suggested that he could take us to the nearest Blue Line station instead because of the traffic. We got off at Washington and headed for the nearest restaurant which happened to be The Italian Village. The food was great so if you happen to be in the neighborhood, go check it out.

After eating we went out for some shopping. The others stopped by a big shopping center to buy some jeans and other stuff. I took off and headed for The North Face shop in the famous John Hancock Center. Once I was done there I headed over to an Adidas store nearby to get some shoes.

I met up with the rest of the guys at the top of the Hancock Center for a beer and a break. The view of the city up there is pretty amazing. We didn’t step outside though and the bar was full so we had to sit someplace else.

Once out of the building we took a cab back to the hotel. Our flight left early the morning after so we headed for our rooms to pack our things and just relax.

And that’s it for this years php|tek!

May 26, 2008

Zend_Service_Recaptcha proposal

Filed under: PHP, Technology — Tags: , — christer @ 11:19 am

A little while back I wrote a set of classes in PHP to fetch a reCAPTCHA instead of using the libraries they offer (which is just a set of functions). I checked to see if there was a proposal for a reCAPTCHA ZF component and Pádraic Brady had a proposal placeholder in the wiki. There was no relevant information in the proposal so I restructured my stuff a little to make it “ZF compliant” and sent Padraic an email about it.

The proposal has been updated and I’m co-proposing it with Pádraic and you’ll find it over at the ZF wiki.

May 24, 2008

Chicago - Day 4 (php|tek - Day 2)

Filed under: PHP, Trips — Tags: , — christer @ 4:22 am

It was a tad bit hard to get up this morning but I managed to attend the following talks:

  1. Test Driven Design in PHP by Jason Sweat
  2. Of Haystacks and Needles by Derick Rethans
  3. PEAR, Phar, and Smart PHP Application Deployment by Greg Beaver
  4. Help, my website has been hacked, now what? by Eli White

After talking to some of the other guys I wish I had went to Performance Tuning MySQL by
Morgan Tocker instead of the Phar talk that was IMO pretty boring and left me with nada. I guess it’s hard to be more specific on the topics when you only have one hour as I wrote earlier…

Anyways, I met up with Shahar Evron from Zend that had a course for some of us at VG last year. I had hoped to grab a beer later on with him but we didn’t find each other so we’ll take it some other time.

After the talks I relaxed a bit before heading over to Gibson’s with the NRK and Dagbladet guys. Erlend was at a family dinner since he has some family here in Chicago and Peter went downtown with Espen and Espen from Go Mobile. This time I had brought my passport so I could enjoy some Samuel Adams with the food over at Gibson’s but this time they didn’t ask us for ID at all!

After the steak orgie I headed over to Shoeless Joe’s with Andreas and one of the guys from Dagbladet for a couple of beers. We were all pretty stuffed from Gibson’s so we didn’t stay at Joe’s for very long.

Last year we went downtown Chicago every day after the talks but this year we have been more around the hotel which has been very ok actually. Several hours of talks each day is pretty exhausting and it’s nice to take it easy once in a while. It’s also pretty boring to spend 45 minutes on the rapid transit each way…

And once again … that’s it for today!

Chicago - Day 3 (php|tek - Day 1)

Filed under: PHP, Trips — Tags: , , , — christer @ 4:01 am

So, the first official day of php|tek 2008. Andi Gutmans held the keynote which was very good. I’ll post some links to presentations once I find them.

On the first day I attended the following talks:

  1. Choosing RIA technologies by Josh Eichorn
  2. State & Ajax - How to maintain browser, and application state in an asyc world by Paul Reinheimer
  3. XQuery: Next Generation Data Access, Today by Kitman Cheung
  4. Building Distributed Web Applications by Jason Rexilius
  5. Facebook performance caching by Lucas Nealan

It’s quite exhausting to go through all this in a day and at the end of the day it’s hard to stay focused. It might be better to have each talk last about 2 hours and be more in-depth instead. Some of the talks I have attended are quite basic stuff, and I think it’s a waste of time to do that at a conference such as this one. People don’t come here to learn basic php, right?

After all the talks we went to our rooms and relaxed a bit. I got to write some posts and uploaded some photos to my flickr account.

Later there was a Rockband battle here at the hotel which was quite fun. Paul Reinheimer and some other guys had dressed up as Kiss and was rocking out when I got there. Microsoft sponsored the event and the drinks were on the house for the first hour (and then became ridiculously expensive). I had some experience from Guitar Hero III on my 360 and we formed a band called Fjord that consisted of me on guitar, Andreas (from NRK) on vocals, Fredrik (also from NRK) on drums and another guy (Mike?) on bass. We failed miserably and didn’t qualify for the second round. I totally blame the other guys!

After the Rockband battle we headed over to the hotel bar for some drinks where we met up with two guys from Dagbladet (another Norwegian news paper) and some other guys from Sweden. We had great fun and then headed over to a nearby bar called Shoeless Joe’s and stayed there for a while having fun. To get there we had to play frogger across the main highway right by the hotel. Since it was pretty late it was not that much traffic though.

And that’s it! Another day gone by in Chicago!

May 22, 2008

Chicago - Day 2 (php|tek Tutorial day)

Filed under: PHP, Trips — Tags: , , , , — christer @ 11:44 pm

Today I got up early after a really good nights sleep to register for php|tek. This was the in-depth tutorial day and each talk lasted for 3 hours. I went to Working With Web Services by Rob Richards and Testing with PHPUnit and Selenium by Sebastian Bergmann.

I’ll try to write some posts about unit testing in php using PHPUnit sometime soon since Mats and I will use that allot for a project we are doing together.

After the tutorials I headed back to the hotel room for a quick rest. I met up with the NRK guys a bit later and we took the metro to Damen to get something to eat. Andreas wanted to visit a comic book store there as well to pick up some more comic books.

We decided to eat at a place called Earwax Cafe. It was a pretty good choice since the food there was really good! After a little while we headed over to a place called Nick’s Beergarden to grab some beers before heading back to the hotel.

And thats pretty much it for this day.

May 20, 2008

Norwegian PHP Testfest

Filed under: PHP, Technology — Tags: , , , — christer @ 5:01 pm

The Norwegian PHP User Group is hosting a Testfest on the 29th of May. My friend Mats is probably going there but I can’t make it that day. I’ll check the code coverage list and see whats missing and maybe I’ll write some tests and submit them.

Older Posts »

Blog at WordPress.com.