Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading files outside the webroot

Tags:

php

apache

plesk

OK, firstly apologies as I realise that this is a topic which has been covered many times before - believe me I know, I've read all of the previous questions and answers and still can't get this to work.

I have a folder containing downloadable files. For security purposes I've located this file outside the webroot. However, despite my best efforts, I can't get my php script to download the file.

I'm using a Linux VPS Apache Server using Plesk 11.

The (simplified) file structure is as follows. The httpdocs folder is the webroot. The private/uploadedfiles folder is where I want to download from.

-var
 - www
  - vhosts
   - mydomain.org.uk
    - httpdocs (webroot)
    - private
     - uploadedfiles

I'm using a jQuery ajax call to pass the filename to a PHP script called downloadscript.php. This script sits within the httpdocs webroot. The script is as follows:

<?php

$filename = $_POST['fbpath'];
$path = '/var/www/vhosts/mydomain.org.uk/private/uploadedfiles/' . $filename;

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($path));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($path));
ob_clean();
flush();
readfile($path);
exit;

?>

The ajax call is working with no issues, but I'm getting the following error message on my PHP logs:

 PHP Warning: readfile(/var/www/vhosts/mydomain.org.uk/private/uploadedfiles/filename.docx): failed to open stream: No such file or directory

I have checked, double checked and triple checked and the file definitely exists on inside the uploadedfiles folder.

I have also checked that it isn't an open_basedir restriction issue - I'm pretty sure it isn't.

I'm sure there's something really simple I'm missing - where am I going wrong?

As an additional extra, I haven't written the script for uploading files yet - is there anything I should know in advance before going ahead with this?

Thanks!

like image 866
Chris Avatar asked Dec 11 '14 13:12

Chris


1 Answers

After much trial and error, I appear to have solved the problem.

The issue was in using jQuery/Ajax.

When I changed the way the downloadscript.php file is accessed to a direct $_GET request from the link on the page, it worked a treat.

Anyway, thanks for your help everyone!

Chris

like image 120
Chris Avatar answered Oct 17 '22 20:10

Chris