Archive for the ‘Server-side scripting’ Category

PHP foreach loops pass arrays by value

Sunday, December 17th, 2006

I nearly lost my mind debugging a problem with some PHP I’d written awhile back that wasn’t working as I’d expected on one server (but fine on my own.)

After many hours of cursing myself for not having a better debugging system, I discovered it was a PHP 4 versus PHP 5 code incompatibility. Turns out that PHP passes arrays into foreach loops by value, which means that any changes you make to that array inside the foreach don’t appear after the foreach, because it’s acting on a copy of the arrray instead of the original data.

So code like this:

Doesn’t print “nothingnothing”, which is what I’d expect; it prints “rainbowspuppies.” In PHP4, apparently, there’s no way to get around this. In PHP5, you can pass the array into the foreach by reference using this notation: foreach ($gina->interests as & $interest)

For now, I to make my code both PHP4 and PHP5 compatible, I went with a:

while ($i=0; $i < sizeof($gina->interests); $i++)

Which just isn’t as readable as the foreach. Here’s the PHP doc on foreach (which clearly states the PHP 5 caveat.)

Graphing Amazon sales rank, or automated author navel-gazing

Saturday, December 2nd, 2006

Like most authors tasked with promoting their new book, checking Lifehacker the book’s Amazon sales rank has become part of my daily routine. But your book’s sales rank is one of those things - if you obsess about it too much, you’ll lose your mind. “It’s total B.S.,” a writer friend told me. “My agent told me it’s a miniscule representation of your book’s sales overall.” That’s probably less true for tech books than fiction, but either way, I wanted a way to capture my sales rank over time without constantly checking myself like an anxious freak. A number alone after awhile is pretty meaningless, and it literally changes by the hour.

So, inspired by PB’s graphing post and a curiosity about Amazon’s API, I set out to write a little something that would help me visualize what’s happening with the book’s sales over time. I didn’t get into the hardcore tools Paul did - just the names RRDTool or SNMP scare me - so I instead opted for the very no-frills, Flash-based PHP/SWF graphs. After registering for a free key, I was delighted to find that the Amazon API is dead simple. In less than 30 minutes of a little PHP/MySQL hacking, I had a sales rank capture-and-graph set of PHP scripts. It’s turned out to be a really nice way to keep an eye out without reloading the book’s Amazon page 4 times a day like a total egotistical loser.

Here’s the finished Lifehacker book Amazon sales rank charter. Screengrab below:

Amazon sales rank charter

Saturday, September 30th, 2006

Rasmus Lerdorf’s PHP5 talk at Yahoo! Open Hack Day covered how to squeeze the most performance out of your PHP pages. (This mailing list message from earlier this year covers how to use valgrind and KCacheGrind as well.) Very enlightening.

Banging out an AIM bot

Sunday, June 25th, 2006

I’m not a Perl developer by any means (Python’s my poison) but I wanted to build a quick AIM bot, and Perl’s OSCAR.pm lets you do it in less than 20 lines of code. It’s insane how simple this is:

use warnings;
use strict;
use Net::OSCAR qw(:standard);
my $oscar;
$oscar = Net::OSCAR->new();
$oscar->set_callback_im_in(&im_in);
$oscar->signon($screenname, $password);
while(1)
{
$oscar->do_one_loop();
}
sub im_in {
my($oscar, $sender, $message, $is_away) = @_;
print "[AWAY] ” if $is_away;
print “$sender: $message\n”;
$response = “Hello”;
$oscar->send_im($sender, $response);
}

I wrote a bot which executes a shell script that reads and writes to your todo.txt (more on that in a minute.) Mark ran with the idea and we discussed keeping a bot that can run other scripts on your computer, like “open VNC port” instead of using port knocking or leaving your server port open at all times. The trick is the bot only runs commands from authorized AIM names. I’m not sure how secure that is, but it is a neat idea.

Build Your Own AIM Answerbot [On LAMP]

FileChucker: AJAX File Upload Script with Progress Bar

Friday, February 24th, 2006

FileChucker’s a $15 Perl script that provides an Ajax-y file upload interface for your web site, complete with progress bar. Haven’t tried it, but looks pretty cool.

FileChucker: AJAX File Upload Script with Progress Bar [Encodable Industries]

Quote of the day

Thursday, December 22nd, 2005

“The main class is like a three thousand line Perl file. Run as CGI!!! That’s like, fifty times wacko!”

Lifeblog (mostly Atom) Posting Protocol Example

Sunday, December 4th, 2005

I’ve been using Nokia’s Lifeblog software on both the PC and my phone to post to my cameraphone blog for months now and having a ball with it. (See my review of Lifeblogging with the Nokia 7610 for more info.)

Right now I’m using TypePad to host the web part of it, but if I ever want to build the capability into Scribblish (and I will) Robert Price has a nice walkthrough on how he did it for his homegrown PERL-based CMS. Also of interest alongside this - an Atom PHP implementation.

Robert Price - Lifeblog Posting Protocol Example [Robert Price]
PHP AtomAPI Implementation [Isolani]

Getting started with PHP

Tuesday, November 22nd, 2005

Someone asked me today about where to get started learning PHP. There are so many ad-covered pop-up launching PHP tutorial/community sites out there that teach you how to learn PHP3, I told him to check out the tutorial from the horse’s mouth on PHP.net, and a nice beginner area on the Zend site as well. Any other good ones I missed?

Getting Started [PHP Manual]
Absolute Beginners [Zend]

Phoogle Maps 2.0

Monday, November 21st, 2005

Drop a Google Map onto your web page with PHP, easy as pie with Phoogle and a Google Maps API key. Gawker Stalker’s crying out for this.

Phoogle Maps 2.0 [system7designs via digg]

The Singleton Design Pattern for PHP

Tuesday, October 18th, 2005

Singleton’s come in handy for things like, oh, access control lists. (Thanks, Mark.)

The Singleton Design Pattern for PHP

Mac OS X Packages - PHP

Tuesday, October 18th, 2005

Thank you, Marc Liyanage, for not making me build PHP5 for my Powerbook.

Marc Liyanage - Software - Mac OS X Packages - PHP

PHP MVC

Sunday, September 18th, 2005

A couple of buddies and I have been doing some testing and research into Model View Controller frameworks in PHP. In the process, I did the PHP Cake tutorial in which you build a simple blog engine. Cake aims to be the Ruby on Rails of the PHP world and does well. While it is impressive, it’s not quite what we’re looking for. (More on the other app I wrote with Cake later.)

I tried PHP MVC, and I’m not sure if I or the developers should be embarrassed about the fact that I couldn’t get the example app to run (as in, unintelligable error in my logs.) Neither could either of my cohorts.

Long story short, this OnLAMP article tackles MVC in PHP, and begins to build a custom MVC framework, which it looks like me and my co-coders are going to do as well with a new app we’re building - though not exactly the way the author is going about it. Still, timely article with lots of good info.

Understanding MVC in PHP [ON Lamp]

Perl global search and replace

Tuesday, September 13th, 2005

I produce a monthly web magazine which consists of eight years worth of flat HTML files. One of the writers, who recently got a new email address, asked me to update it everywhere it appeared on the site - which was in dozens of .htm and .html files nested in subdirectories all over the tree. The very thought gave me a headache.

But, after a little researching, I found this quick Perl script did the trick on files piped from the find command:

[trapani@colossus html]$ find . -name “*.htm*” | xargs perl -pi -e ’s/user\@oldaddress.com/user\@newaddress.com/g’

Scary, running that sucker a bit recklessly on the production server, but it totally worked, and fast. Modified from the suggestion at this O’Reilly Linux Server Hack.

View live site referers

Tuesday, September 6th, 2005

Programmer Dean Allen’s free PHP/MySQL app, Refer, displays live real-time referring URLs to your web site.

Of course, one could just watch one’s site logs to get an idea of who’s clicking in from where. But Refer filters out certain types of files (CSS, JS, etc), referers from your own domain, and can exclude certain directories, too. (Like, I don’t want to see any referers generated while I’m working on a post in WordPress.)

I’ve used Refer for several months now on my other site, and besides occassional referer spam problems, it’s a fantastic way to see immediately if your site is getting a whole lot of traffic from fresh links.

The downside of Refer is that it requires a database insert on EVERY request for pages for which you want referers recorded. This can slow things down considerably, and perhaps give your conservative performance-concerned sysadmin indigestion. Refer uses this neat .htaccess line which automatically adds the PHP script to the end of each page for processing:

php_value auto_prepend_file /www/ginatrapani/refer/refer.php

Not sure how long I’ll keep this unpassworded, but here’s Spun’s installation of Refer so you can check out how it works yourself..

Refer 2.1 [Textism]

How to use the robots META tag

Thursday, September 1st, 2005

The robots <meta> tag in the <head> of your web page tells well-behaved robots (like the Googlebot) whether or not to index a page and whether or not to follow links on a page. For bloggers and zine publishers, robots should only index the permanent locations of posts, not the ever-changing front page or archive pages.

To use meta tags to direct the Googlebot to your permalinked post locations, insert the following in the <head> on your front page and archive pages:

<meta name="robots" content="noindex,follow" />

That says, “Hey bot, don’t index this page, but follow the links.” You don’t want these pages indexed because they will change every time you post to your site. The posts’ permanent locations, which should be linked on your front page, will never change however, and so the robot should follow the links and index them. Those permanent locations of your posts should have the following in the document:

<meta name="robots" content="index,follow" />

Alternately, if you don’t want the links in your posts followed but you do want your posts added to the search engines’ indices, use:

<meta name="robots" content="index,nofollow" />

To achieve this in a WordPress template or any PHP page where $single is set if you’re viewing a single post’s permalinked location, insert the following into the templates that include <head> tags:

<meta name="robots" content="<?php echo (!$single?'no':''); ?>index,follow" />

HTML Author’s Guide to the Robots META tag [robotstxt.org]

iTunes Library reports

Wednesday, August 31st, 2005

Developer Alex King’s released a PHP/MySQL app that imports your iTunes library and displays reports like your top rated artists based on number of songs.

The code imports iTunes’ Library.xml into 3 MySQL tables using PHP 5’s XML libraries, like this:

Even Alex says that’s “an ugly hack.” What’s the better way to handle it without the output buffering?

Either way, I’ve posted my iTunes library reports using Alex’s app.

alexking.org: Blog > iTunes Stats [Alex King]

Highlight PHP source in HTML

Tuesday, August 30th, 2005

PHP’s highlight_string function formats and colorcodes PHP source in HTML, which will come in very handy for publishing code snippets on this site.

For example, a simple class called Greeter echoes “Hello, $x” to the screen. It’s source code is formatted with colors and indentation for HTML like this using highlight_string:

Here’s Greeter’s output, and here’s the source view.

highlight_string [PHP manual via Beginner's PHP]