Feed file outside of public_html

2.4k views Asked by At

I am having trouble uploading a file to the user from outside of "public_html" which is the folder that everyone has access to thru http. Ex. www.website.com/ everyhting after the / is public_html. I'm sure you all know what I'm referring to.

So I have this script that should read a file (sample.pdf) from (server perspective) /images/protected/ but PHP won't find my file. Am I doing this wrong?

<?php
$file = '/images/protected/sample.pdf';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
} else {
    echo "404 - FILE NOT FOUND!<br />\n";
    echo "File: $file";
}
?>

Every time I execute this script I get the 404 - FILE NOT FOUND!<br />\n instead of a file download.

2

There are 2 answers

1
Rob W On BEST ANSWER

You have to supply the absolute system path. Currently, you're requesting a file at /images/..., rather than /var/www/hosts/whateverdomain/images/....

$file = $_SERVER['DOCUMENT_ROOT'].'/images/protected/sample.pdf';

If your file is really located at /images/protected/, make sure that you have sufficient permissions to read that file.

0
Axel Latvala On

Turns out I am on shared hosting so the right "root" path for my website was /home/me/