MENU

Make a link to a file

  Previous article Next article  

User Defined Tag to create a link to open a file, followed by the file size.
This article originated from the former CMSMS Wiki and the original author is Ralph Kutschera
The UDT forces the download of the file now! [HTML5!]

Create a new User Defined Tag, named "file_link" and copy-paste the following code in it:

file_link
$url = isset($params['url']) ? $params['url'] : '';

// check if file exists
if(file_exists($url))
{
  $linkname = isset($params['name']) ? $params['name'] : $url;

  $filesize = filesize($url);
  // beautify filesize
  $suffix = "B";
  if($filesize > 1024)
    {
      $filesize = $filesize / 1024;
      $suffix = "KB";
      if($filesize > 1024)
      {
        $filesize = $filesize / 1024;
        $suffix = "MB";
        if($filesize > 1024)
        {
          $filesize = $filesize / 1024;
          $suffix = "GB";
        }
      }
    }

  $filesize = sprintf("%.2f", $filesize);

  // edit this line, if you want a different representation of your link
  echo '<a href="'.$url.'" download><b>'.$linkname.'</b> ('.$filesize.$suffix.')</a>';
}
else
{
  // this is shown if the file you try to link can't be found
  echo $linkname.' (Sorry, file not found)';
}

You can omit the tag attribute 'name' if you want the name of the file as the link text. The code also checks whether the file does exist and gives a '(Sorry, file not found)' otherwise.

  How to use

{file_link url='uploads/path/to/file.pdf' name='My filename'}

Or in a module template you can do something like:

{file_link url=$foo->url_to_file name=$foo->name_of_file}

  Working example

I use this UDT to download a .XML file in my blog FormBuilder template and stylesheet


Advertisement


Ads help me to help you! Thanks!

Ads help me to help you! Buy products from these advertisers!


  Show related articles:


  Comment Form

Click here to open the form


  0 Comments

No comments yet...

CMS Made Simple - Tutorials, tips and tricks - CMSMS

Make a link to a file

  Article optimized for CMSMS 2.x

  Author:
  Last tested in: CMSMS 2.2.5
  Last updated: 23-06-2018
  Comments: 0
  http://cms.ms/aVKp

Advertisement


Ads help me to help you! Thanks!

Ads help me to help you! Buy products from these advertisers!

Advertisement


Ads help me to help you! Thanks!

Ads help me to help you! Buy products from these advertisers!