Good News / Bad News

The good news: PHP has lots and lots of useful built-in functions for all sorts of things.

The bad news: PHP has lots and lots of useful built-in functions I don’t know about.

Sometimes it’s almost an embarrassment of riches. You think you know PHP pretty well and know how to write some pretty slick code. In a thread at PHPBuilder.com I threw together a bit of code to build a CSV file from a database query. I figured I was being fairly clever using the uniqid() function to create a unique file name I could use for temporary storage of the CSV data, fopen()-ing it and then eventually using readfile() to output it to the user, followed by an unlink() of the file once it’s done.

Then fellow moderator “Weedpacket” pointed out to me the tmpfile() function, which I’d never run into before, and which makes it easy to open up a temporary file. It returns a file handle similarly to the fopen() function. The nice part is that you do not have to worry at all about generating a unique name, and the file is automatically deleted upon script completion (or when you fclose() it should you choose to).

It serves as a slightly humbling reminder that when working with PHP, before you write code to do something that someone else has likely had to do in the past, it is probably worth your while to scan through the function lists of applicable sections of the manual to see if there is already a built-in function which does what you need. It is often worth the time to make that search, as the built-in functions are likely to be faster than your own user-defined functions, plus hopefully they should be more robust.