Display file size and extension using PHP

June 8, 2014   |   1 minute read.

If you want to display attached files on your, post, page or whatever, you may want to display the file size and the extensions. This Snippet will do the trick. Depending on what sort of file are you working on you can display and customise this function:

function get_the_file_values($file){

    // Getting path info file
    $path_parts = pathinfo($file);
    // Getting file size
    $ch = curl_init($file);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, TRUE);
    curl_setopt($ch, CURLOPT_NOBODY, TRUE);

    $data = curl_exec($ch);
    $size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
    $size = size_format( $size, 2 );


    $value = array();

    // We switch the file extension and we return the required data.
    switch ( $path_parts['extension'] ):

        case 'pdf':
            $value = array( 'ext' => 'pdf', 'desc' => 'PDF Document', 'size' => $size );
            return $value;
        case 'mp3':
            $value = array( 'ext' => 'mp3', 'desc' => 'MP3 Audio File', 'size' => $size );
            return $value;
            $value = array( 'ext' => 'file', 'desc' => 'Attached File', 'size' => $size );
            return $value;