I used this php file download code for a long time, to allow someone to click on a link and either view or download the file. But What I could never do is get it to work without the PHP code being in the same directory as the files I was accessing. Today I tried to put the PHP code in a directory called /scripts, access it from an html file back at the root “/”, and use it to get a file in /pubfiles. Unfortunately I just can’t get anything beyond a log output to actually access the file, as a full path.
html call basically looks like this…
[code=html]<a href=”/scripts/fetchAfile.php?file=Candle.h&filePath=/pubfiles/&view=0″>Get Candle.h</a>
So I’m passing 3 params to the php code. Please forgive some junk in the file, the result of my experimenting with stupid ideas to fix.
[CODE]<?php
$filePath = ‘/private/files/’; // default area
$fileName = ‘ ‘;
$view = ‘1’; // assumed. If 0, just download, else view
$type = ‘view’;
$ext = ‘pdf’; // default type
$logFile = ‘downloads.log’;
if(empty($_GET[‘file’])) {
notFound();
}
if (!empty($_GET[‘filePath’])) {
$filePath = $_GET[‘filePath’];
}
$view = $_GET[‘view’]; // to decide between download or browser display
$fileName = basename($_GET[‘file’]);
$fullViewPath = $filePath . $fileName;
// get file extender for application type, for browser
$ext = pathinfo($fileName, PATHINFO_EXTENSION);
// log request if we get here
if ($view == 0) $type = ‘download’;
$current = file_get_contents($logFile);
$current .= “rn” . $fullViewPath . ” ” .$type . ” Request at ” . date(DATE_RFC2822);
file_put_contents($logFile, $current);
if(!file_exists($fullViewPath) or !is_readable($fullViewPath)) {
notFound(); }
if ($view == ‘1’) { header(‘Location: ‘ . $fullViewPath); } // display in browser
else // just download
{
header(‘Content-Type: application/’ . $ext); // specify app with file extender
header(‘Content-Disposition: attachment; filename=”‘.basename($fileName).'”‘);
readfile($fullViewPath);
}
function notFound()
{
global $fullViewPath;
error_log(“rn ** file unreadable: ” . $fullViewPath);
header(‘Location: http://elfintechnologies.com/404.shtml’);
exit;
}
?>
So the result is, the php file is definitely found at scripts, because it does dump log and error files. now notic I’m forming a full path ($fullViewPath) by combining the passed file path ($goes to $filePath) with the file name file (goes to $filename) The logfile bears out that the path is correct…
/pubfiles/Candle.h download Request at Thu, 04 Jan 2018 10:12:24 -0700
So the $fullViewPath variable is definitly correct. Unfortunately file_exists() and is_readable() both fail…
[04-Jan-2018 10:41:43 America/Denver]
** file unreadable: /pubfiles/Candle.h
Well I don’t know why its not found or readable, and again, if I put the php in the same directory as the files to be downloaded, and adjuest the HTML link accordingly, everything goes smoothly. So obviously I’m missing something very basic about specifying directory locations. Thanks for any help