wordman
wordman

Reputation: 581

How do I access files placed outside of the site root?

I have fried my brain all day on this. Researching SO until my eyes are bleary...I need to know: How do I access files placed outside the site root?

Background: Apache 2.0 dedicated server running Linux.

Code: PHP and MySQL

Reason: I want the files to be secured against typing in the file path and filename into a browser.

This can't be that difficult...but my splitting head says otherwise. Any help would be absolutely appreciated.

Upvotes: 4

Views: 18233

Answers (2)

pjmorse
pjmorse

Reputation: 9294

Have a look at the answers to this question, which seem to be doing more or less the same thing.

A quick summary: readfile() or file_get_contents() are what you're after. This example comes from the readfile() page:

<?php
$file = 'monkey.gif';

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;
}
?>

I don't recommend allowing the $file variable to be set using user input! Think about where the filenames are coming from before arbitrarily returning files in the response.

Upvotes: 4

zzk
zzk

Reputation: 1387

are you trying to access files outside of site root? Then you can look at this link in stackoverflow. And this is the official doc in Apache.

Otherwise you don't have to do special handling to prevent others from accessing files outside site root.

Upvotes: 0

Related Questions