Menü schliessen
Created: March 4th 2021
Last updated: March 4th 2021
Categories: Advanced Custom Fields,  IT Development,  Php,  Wordpress
Author: Marcus Fleuti

[HOWTO] get filesize in MB from file array in PHP with ACF

Tags:  ACF,  array,  byte,  file,  filesize,  mb,  PHP
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

You are uploading some files over an "Advanced-Custom-Field" and want to read the filesize of the document, maybe for some user information about the size of the file which is getting downloaded.

Firstly make sure that you are returning a File Array instead of just returning a File URL as seen in the picture below:

Logic / Funcionality

To get the filesize there is no need to be extremely skilled in PHP. All you need is to know is...

  • how to calculate from Bytes to MegaBytes
  • how to access ACF-Fields
  • how to access Array / Object items in PHP

If you are already familiar with the three point above you can start with accessing the filesize of the file. You can access the filesize by firstly getting the field like in the code below (we are using ACF default function for getting the content / return values of a field):

get_field('your_field', $post->ID);

Inside of this "File Array" you have now every information you need to display the file or calculate the filesize. The filesize is stored in Bytes, so we have to do some conversion work right here to get MegaBytes. Actually we are just multiplying the Bytes with
10-6 (0.000001):

$your_file['filesize'] * 0.000001;

Coool! Now we have the filesize in Megabytes but it is still a float value with lots of decimal places. If you don't need this precision you can simply round the number with the PHP round() function:

round(3.2222222, 0);

Everything is rounded now and we have no decimal places left. You can append MB to the number in case you want to display the size of the file for the user.