I’ve been working on a website that includes a download button. When clicked the button would prompt to open or save the file. The prompt appeared on cue and the file downloaded, but for some reason the file was empty.
Checking the php_error.log, showed that this error was being generated:
PHP Warning: filesize() [function.filesize]: stat failed for http://localhost:8888/ringstone/wp-content/uploads/docs/brochure.pdf in /Applications/MAMP/htdocs/ringstone/wp-content/themes/ringstone/frontpage.php on line 26
Normally if the filesize function fails it’s because the directory where the file is stored is not writeable or the file is larger than 2GB.
In this case, the directory was writeable and the file was a lot less than 2GB in size. So I was stumped.
Going over my code, the only thing that I could see that might be causing the problem was the link to the file.
I was using the following code to get the WordPress uploads directory:
$uploads = wp_upload_dir();$url = $uploads['baseurl'];$filename = $url . ‘/docs/brochure.pdf’;
This generated the url for the document as: http://localhost:8888/ringstone/wp-content/uploads/docs/brochure.pdf
According to the PHP manual for filesize, as of PHP 5.0.0 the filesize function supports using some URL wrappers, including HTTP. The version of MAMP that I’m using includes PHP 5.3.2, so this shouldn’t have been a problem. It turns out that I was wrong.
I updated my code to:
$uploads = wp_upload_dir();$path = $uploads['basedir'];$filename = $path . ‘/docs/brochure.pdf’;
And it worked.
The lesson is that if you’re seeing filestat error in your PHP error log, then go through the following checklist:
- Pass filestat the directory path to the file, not the URL. (Even though the manual says that it should work.)
- Check that the directory is writeable.
- Check that the file is smaller than 2GB in size.