Category Archives: PHP

WordPress and the”filesize() [function.filesize]: stat failed”Error

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:

  1. Pass filestat the directory path to the file, not the URL. (Even though the manual says that it should work.)
  2. Check that the directory is writeable.
  3. Check that the file is smaller than 2GB in size.

PHP Code Snippet

Because of the re-design, there’s a lot of broken links – mainly because the blog used to live under the /whatithink/ folder on the server and now resides in the root folder. So all those Google links now point to a part of the site that no longer exists.

So anyone coming here from Google is going to get a 404 error. Not good.

While I get my head around using .htaccess to automatically rewrite the broken URLs, I’ve created a 404 page that will, (hopefully), correct the URL.

Here’s the PHP:

$requested = $_SERVER['REQUEST_URI'];$parts = explode('/', $requested);foreach ($parts as $part) {switch($part) {case ('whatithink'):break;case (''):break;default:$out .= '/' . $part;}}$out = 'http://' . $_SERVER['HTTP_HOST'] . $out;

Because all my broken URLs have an extra “/whatithink/” section, I can just break the requested URL into parts, and rebuild it without that section.