Skip to content

Instantly share code, notes, and snippets.

@morgyface
Last active May 26, 2022 08:49
Show Gist options
  • Select an option

  • Save morgyface/725df3cb655db3f8de395b9db4fa80fc to your computer and use it in GitHub Desktop.

Select an option

Save morgyface/725df3cb655db3f8de395b9db4fa80fc to your computer and use it in GitHub Desktop.
WordPress | File size from URL
<?php
// Return a neat file size
function nice_file_size($file_url, $precision = 2) {
$nice_file_size = null;
$attachment_id = attachment_url_to_postid($file_url); // Gets ID of file from URL
$file_path = get_attached_file( $attachment_id ); // Gets path using ID
if ( is_writable( $file_path ) ) { // Locally an error is thrown due to file not being writable
$size = filesize( $file_path ); // NB filesize only works with the path to the file NOT a URL
$base = log($size, 1024);
$suffixes = array('', 'KB', 'MB', 'GG', 'TB');
$nice_file_size = round(pow(1024, $base - floor($base)), $precision) .' '. $suffixes[floor($base)];
}
return $nice_file_size;
}
?>
<?php
// Example
echo nice_file_size($download_url, 0);
?>
@morgyface
Copy link
Author

File size from URL

This seems crazily verbose but it should be fairly robust and versatile. The previous version relied on you getting the file ID before passing it into the function. This works using just the file URL, containing the process within the function.

The thing to make note of is; the difference between path and url. They're two different things, and the php filesize function only works if you give it the server path to the file, hence why we use attachment_url_to_postid to convert the URL to a WordPress ID and then get_attached_file to get the path. Seems like we're going round the houses but we're not.

$precision is just the number of decimal places you want the file size to display, it defaults to 2 but can be changed to suit. The example uses 0.

Obviously this will only work with files uploaded through the dashboard.

Hope it helps someone else. Big hugs from Cornwall, UK.

@morgyface
Copy link
Author

Updated May 2022

I discovered that, when working locally, files are typically unable to be accessed due to permissions. This causes filesize to print an error. I've therefore added a condition if ( is_writable( $file_path ) ) { which ensures the file is accessible before running filesize. Probably not a bad condition to have in place regardless of whether you're working locally or not.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment