PHP "Gotcha"'s

Whilst PHP is a fairly nice language for rapid development of dynamic webpages and simple web apps, it encourages sloppy coding practices, and has some rather braindead features.

I'm using this page to dump a list of things to watch out for.

Inconsistent naming

Some functions have been renamed between different versions of PHP, causing trouble for scripts which will work under one version of PHP but not another.

Good example is stream_set_timeout() which was called set_socket_timeout(), then changed to socket_set_timeout(), and finally its current name, stream_set_timeout(). Not good.

The tmpnam() function

The tmpnam() function takes two params, dir and prefix. It will, sometimes, create a temporary file in the directory given, with the prefix requested, and a randomly-geneated part, and return the name of the file it created for you.

According to the PHP tempnam() documentation:

Creates a file with a unique filename in the specified directory. If the directory does not
exist, tempnam() may generate a file in the system's temporary directory, and return the name of that.

Statements like “may generate a file” don't sound too good.

It boils down to - if tempnam() likes the dir name you pass it (the dir exists, and is writable by the user the script is running as), it might create a temporary file there. On the other hand, it might just ignore what you asked for, and go create a file in the system temp dir instead (i.e. /tmp).

If you're running PHP with open_basedir() restriction in effect, /tmp is most likely outside your open_basedir() setting, so the attempt will of course fail, with something like:

Warning: fopen(): open_basedir restriction in effect. File(/tmp/wrtETxQDg) is not within the allowed path(s): (....) in file.php on line 31


php/gotchas.txt · Last modified: 2010/02/26 10:45 (external edit)
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki