Make a link to a file

  Previous article Next article  

Make a link to a file

  Article optimized for CMSMS 2.x

  Author:
  Last tested in: CMSMS 1.11.13
  Last updated: 03-04-2015
  Comments: 0

User Defined Tag to create a link to open a file, followed by the filesize.
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
// read parameters
$linkname = isset($params['name']) ? $params['name'] : '';
$url = isset($params['url']) ? $params['url'] : '';

// check if file exists
if(file_exists($url))
{
  $filesize = filesize($url);
  // beautify filesize
  $suffix = "B"; // for Bytes
  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

Show related articles:



A2 Webhosting CMS Made Simple

  Comments

  Click here to leave a comment






This is a captcha-picture. It is used to prevent mass-access by robots. (see: www.captcha.net)
  « Enter the CAPTCHA code (lower case)

Your IP address will be stored on submit. I reserve the right to change or delete your response without notice!
In case of abuse your IP address will be blocked!


Can I have your attention for a moment?

Did this tutorial help you solving a problem at your (clients) website and it saved you many hours of work? Great!!
Consider buying Rolf a cup of coffee in return! [ Click here ]


  0 Comments

No comments yet...

CMS Made Simple 2.2.2 - Tutorials, tips and tricks - CMSMS 2.2.2

Make a link to a file

  Article optimized for CMSMS 2.x

  Author:
  Last tested in: CMSMS 1.11.13
  Last updated: 03-04-2015
  Comments: 0

A2 Webhosting CMS Made Simple