Skip to content

Instantly share code, notes, and snippets.

@starx
Last active February 16, 2017 16:20
Show Gist options
  • Save starx/95c2eb89c04b6b01793933795aaaa2ea to your computer and use it in GitHub Desktop.
Save starx/95c2eb89c04b6b01793933795aaaa2ea to your computer and use it in GitHub Desktop.
PHP Restrict access to file based on created time of the file
<?php
$requestedPath = '...';
$service = $app['service.filesystem'];
$fullFilePath = realpath($requestedPath);
// If the file path cannot be found then stop proceeding
if(!$fullFilePath) die('INVALID');
$fileStat = stat($fullFilePath);
$finalAllowedTimeStamp = strtotime("2017-02-01");
// If the file has been created after the max allowed time then stop proceeding
if($fileStat['mtime'] > $finalAllowedTimeStamp) die('INVALID');
// Continue reading the file
// Get the path information
$filePathInfo = pathinfo($fullFilePath);
// Get the mime type of the file
$mimeType = mime_content_type($filePathInfo['basename']);
// Set the correct headers so that browser can open the file
header("Content-type: {$mimeType}");
header('Content-Length: ' . filesize($fullFilePath));
header('Content-Disposition: filename="'.$filePathInfo['basename'].'"');
readfile($fullFilePath);
die();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment