Created
September 16, 2011 16:19
-
-
Save zeroasterisk/1222467 to your computer and use it in GitHub Desktop.
cakephp file download action, hashed and refer-restricted
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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