Amazon.com redirector

brian_d_foy on 2002-12-29T12:36:03

Now that I listed all the things I am not going to do, I have started to do some of them. I wrote my Amazon.com redirector because it is easily done. I set my Amazon Associates ID with the SetEnv apache directive in my .htaccess file (although you can do it from the server conf file too, but I do not control that on my public website). I also have a private library tree in my cgi-bin directory because I cannot install modules globally, so I add the use lib line. I pull the ISBN directly from the query string since I use this as a keyword search---values do not have names. I just want to add an ISBN to the end of a URL when I make a link, so CGI parameter parsing overkill. If I use a bad ISBN, I stop the script and return 408 to signal a bad request. Not too many people use that, but I like to check for those sorts of errors in the logs. If I output an error page with status 200 I cannot find the errors as easily.

#!/usr/local/bin/perl

use lib qw(.); use Business::ISBN;

my $account = $ENV{AMAZON_ASSOCIATE_ID};

my $isbn = Business::ISBN->new( $ENV{QUERY_STRING} );

unless( ref $isbn and $isbn->is_valid ) { print <<"HERE"; Status: 408 Bad ISBN Content-type: text/plain

ISBN [$ENV{QUERY_STRING}] is not a valid ISBN. HERE

exit; } my $isbn_str = $isbn->as_string( [] );

print <<"HERE"; Status: 302 Ask here, go there Location: http://www.amazon.com/exec/obidos/ASIN/$isbn_str/$account

HERE


A while ago I wrote about tricking people into doing your work by pretending to not being able to do it yourself. Randal took the bait and sent me his program to do the same thing. He likes CGI.pm, but that is okay. His program is more forgiving than mine---he follows Jon Postel's maxim "Be liberal in what you accept, and conservative in what you send" (which first appeared in RFC 761, although later removed, but is in RFC 1122. Alpha geeks probably already knew that, but I did not---isn't Google great?). He outputs a form asking for an ISBN if he does not see one in the input.

Randal also shows proper paranoia by enabling warnings, taint checking, and strictures, even if he does use a magic constant (-1) instead of the symbolic versions (although I think the script pre-dates their addition to the module).

#!/usr/bin/perl -Tw
use strict;

use CGI qw(:standard); use Business::ISBN;

my $num = Business::ISBN->new(param('isbn') || ""); unless ($num and $num->is_valid != -1) { print header, start_html('Give me a valid ISBN'), h1('Give me a valid ISBN'), p, "I need a valid ISBN to proceed to the Amazon.com page", hr, start_form, submit("Suggest this ISBN: "), textfield("isbn","",50); end_form, hr; exit 0; } print redirect("http://www.amazon.com/exec/obidos/ASIN/". ($num->as_string([])). "/stonehengeconsul");