WordPress developers: Write to the filesystem the right way

Many WordPress plugins and themes need to write to the filesystem, to cache data, create a debug log, download libraries that for one reason or another aren’t distributed with the main package, etc. And many of these plugins do it wrong, by writing (or attempting to write) to their own plugin/theme directories. This is a bad idea for a couple of reasons:

  • If you use version control to deploy/manage a site, you probably have configured your repo to ignore the content of dynamic directories like wp-content/uploads. Obviously, you don’t want to ignore plugin and theme directories. When Git etc detects your newly created files, it wreaks all sorts of havoc with workflow and, depending on the content of the files and the carelessness of the deployment manager, poses the risk of losing user content or endangering sensitive data.
  • Some people have their file permissions set very conservatively, so that the webserver user doesn’t have write access to wp-content/plugins or wp-content/themes. So plugins that attempt to write to those directories often break altogether.

The good news is that every properly-configured WordPress installation will have at least one location where the webserver can write, and which is highly likely to be ignored by all version control setups: the upload directory wp-content/uploads. The situation is more complicated on Multisite, where each site has its own subdirectory of wp-content/blogs.dir. Happily, there’s an easy way to concatenate an upload path that’ll work across installations:

[code language=”php”]
$uploads = wp_upload_dir();
$my_upload_dir = $uploads[‘basedir’] . ‘/yourplugindir’;
[/code]

WordPress has a very slick filesystem class that’ll help you if you really do need to write to a plugin or theme directory. But 99% of the time, you don’t. Please keep your stuff out of the codebase.

Leave a Reply

Your email address will not be published. Required fields are marked *