Code snippets category archive

PHP foreach loops pass arrays by value

December 17th, 2006 | Filed under PHP, Code snippets

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.)


Comment cleanup

November 1st, 2006 | Filed under Announcements, Code snippets, WordPress, SQL

UPDATE wp_posts SET comment_status='closed';
DELETE FROM wp_comments;

Sorry folks, comments here on Spun are now disabled - the spam got the better of me. I know, I know, there are plugins to help manage it, but I simply don’t have the time. Email me your thoughts on posts to ginatrapani at gmail.


Create an address book from every message in your sent mail folder

July 28th, 2006 | Filed under Code snippets, Bash scripts

Just noticed that Thunderbird has a new message filtering criteria: “From: email address in my address book.”

That, coupled with Thunderbird’s ability to add the address of anyone you send a message to automatically to your address book, opens up the possibility of filtering mail from people that you’ve communicated with before into “Known” folder, and mail from folks you don’t into “Unknown” folder.

(I’ve been jonesing for something like this for awhile; a helpful Lifehacker commenter pointed out that it’s possible.)

So to get this system going, first I had to populate my address book with all the email addresses I’ve sent mail to before. This one-liner on my IMAP server’s sent-mail file, cobbled together with a lot of help from this Ask Metafilter thread, does the trick:


grep "^To: " mail/sent-mail | grep "@" | \
sed 's,.* <*\([^ ]*@[^ >]*\).*,\1,’ | \
sort | uniq -i | sed ’s/,.*$//’ > correspondents.txt

(Mind you, this Python version is a lot more elegant, but it kept timing out on me. I have a big sent-mail folder.)

From there, import correspondents.txt as a new address book and set up your filter in Thunderbird.

Awesome.

(Also only interesting to me: The ~10k messages I sent from my personal email address in the last 2 years were to less than 2000 recipients, for an average of about 5 messages per correspondent.)


$ wc -l correspondents.txt
1823 correspondents.txt


Customize your terminal prompt

July 16th, 2006 | Filed under Code snippets, Bash scripts

I’m probably going to be embarrassed about this post in the morning, but I re-figured out how to customize my terminal prompt, and I got something that I like which I’ll post here for the next time I get a new computer and have to Google the whole thing up again.

In ~/.bashrc (Mac: ~/.bash_profile), add:


function prompt
{
local GREEN="\[\033[0;32m\]"
local CYAN="\[\033[0;36m\]"
local GRAY="\[\033[0;37m\]"
local BLUE="\[\033[0;34m\]"
export PS1="${GREEN}\u${CYAN}@${BLUE}\h ${CYAN}\w${GRAY}
$ "
}
prompt

Then:


$ source .bashrc

Which makes it look something like this:


gina@amelia ~/Documents
$

But with pretty colors.

That is all.


Banging out an AIM bot

June 25th, 2006 | Filed under Code snippets, Perl

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]

Perl global search and replace

September 13th, 2005 | Filed under Code snippets, Perl

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.


Email address obfuscator

September 4th, 2005 | Filed under Code snippets, HTML, Javascript, Essential Tools

Every time I have to publish a clickable email address on a web page I wind up Googling Javascript tools that obscure the mailto: link and telltale user@example.com format so that spam bots can’t easily pick up the address and tsunami the user with junk.

There are plenty of tools out there, but none that do all that I wanted: namely, encode the ‘mailto’ bit and display a live preview of the link. So I’ve gone ahead and thrown one together of my own.

Go ahead and give it a whirl, it’s got exciting iframe cross-scripting going on for the preview. *

* For now it’s Firefox-only while I work out the IE and Safari compatibility issues. Tested and works now on Internet Explorer 6 with SP 2 on Windows, Safari on Panther and Firefox Windows and Mac.

Javascript Email Address Obfuscator by Gina Trapani

Create a favicon.ico from any photo

September 3rd, 2005 | Filed under Code snippets, HTML, Design, Essential Tools, Browsers

FaviconThe makers of one of my favorite markup/text/code editors on Windows, HTML Kit, have made a web service available which creates favicons out of images.

Favicons are the small images just before the URL in the address bar of many web browsers.* The images are in the .ico file format, so this web service takes any graphic (like a jpg or gif), resizes it and converts it to the .ico format which includes both a 16×16 and a 32×32 pixel version embedded within it.

It’s a tough challenge finding an image that is recognizable at that size, but totally worth it for the visual branding it brings to your site on readers’ and users’ tab bars and bookmark lists.

Once you’ve created an unzipped your favicon.ico to the web server, include the following inside your pages <head> tag to activate the icon:

<link rel="shortcut icon" href="/path/to/your/favicon.ico" type="image/x-icon" />

* Firefox’s support is probably the best, displaying favicon’s on bookmarks, tabs and in the address bar. Internet Explorer’s support for favicons is pretty much nonexistent.

FavIcon from Pics — how to create a favicon.ico for your website [Chami]

Remove default padding and margins

September 3rd, 2005 | Filed under Code snippets, CSS

Most web browsers add default padding and/or margins to certain HTML elements; for example, and unstyled <body> or <p> will have space around it, depending on the browser. To start with no padding or margins, begin your CSS stylesheet with the following:

* { margin:0; padding:0; }

From there explicitly add padding and margins to elements in your stylesheet by declaring CSS classes as usual. See an unstyled page with default padding. Compare it to a page with unpadded elements including the CSS bit above.

Update: Kevin Hale’s quick start CSS templates include the * element above with font-family and font-size, too.


View your cookies

September 1st, 2005 | Filed under Code snippets, Javascript

A quick way to see all the cookies a web page has currently set is to type the following into your browser’s address bar (works in all browsers):

javascript:alert(document.cookie);


How to use the robots META tag

September 1st, 2005 | Filed under PHP, Code snippets, HTML, Search Engine Optimization

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]

Server log IP resolution

September 1st, 2005 | Filed under Code snippets, Traffic stats, Apache web server

Apache’s Logresolve is a little utility translates all those IP addresses in your server logs into English, ie displays 67.19.139.26 as ginatrapani.org. Before my host resolved this site’s logs for me, this batch file on my Windows box resolved logs named something.log and saved them in a folder named “resolved”:

for %%F in (*.log) do "c:/program files/apache group/apache2/bin/logresolve" < %%F > resolved/%%F


iTunes Library reports

August 31st, 2005 | Filed under PHP, Code snippets, XML, MySQL

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

August 30th, 2005 | Filed under PHP, Code snippets, HTML

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]