Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

mysql

apache

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.

like image 827
wordman Avatar asked Oct 23 '25 20:10

wordman


1 Answers

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.

like image 145
pjmorse Avatar answered Oct 26 '25 10:10

pjmorse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!