Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zeroasterisk/1222467 to your computer and use it in GitHub Desktop.
Save zeroasterisk/1222467 to your computer and use it in GitHub Desktop.
cakephp file download action, hashed and refer-restricted
<?php
/**
* Action to download special assets
* example link to download <?php echo $this->Html->link('Link Text', array('action' => 'download', Security::hash('filedownloadsalt'.date('d').env('REMOTE_ADDR')), $filename), array('escape' => false)); ?>
* example URL to download <?php echo $this->Html->url(array('action' => 'download', Security::hash('filedownloadsalt'.date('d').env('REMOTE_ADDR')), $filename)); ?>
* @param string $hash
* @param string $filename
*/
function download($hash=null, $filename=null) {
// check to ensure that the input hash is specific to this user and created today
if (Security::hash('filedownloadsalt'.date('d').env('REMOTE_ADDR'))!=$hash) {
$this->Session->setFlash("Sorry, you are not allowed access to this asset");
return $this->redirect(array('action' => 'failure'));
}
// check to ensure referrer URL is on this domain
if (strpos(env('HTTP_REFERER'), env('HTTP_HOST'))===false) {
$this->Session->setFlash("Sorry, you must access this asset from within my site, not directly");
return $this->redirect(array('action' => 'failure'));
}
// now get the asset
$filenameParts = explode('.', $filename);
$filenameExt = array_pop($filenameParts);
$filenameBase = implode('.', $filenameParts);
$this->view = 'Media';
$params = array(
'id' => $filename,
'name' => $filenameBase,
'download' => true,
'extension' => strtolower($filenameExt),
'path' => APP . 'files' . DS, // don't forget terminal 'DS'
'cache' => true,
);
$this->set($params);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment