使用php发送文件而不暴露目录

These are my settings:

Web Server: Apache/2.4.25
Web structure:
 /
 |__Video/
         |__ test.mp4
 |__play.php

Currently I am exposing all my videos on my server putting directly the video directory in the apache directory.

What I want to obtain is to move the video outside the Apache directory (assume no permission problems) and trasmit only the requested video through a GET request to play.php like: GET play.php?req=test.mp4

Currently I've written the following code:

$name = $_GET['req']
header('Accept-Ranges: bytes');
header('Content-Length: ' . filesize($name));
header('Content-Type: ' . mime_content_type($name));
header('Content-Disposition: filename="'.$name.'"');
readfile($name);
exit;

What is missing? Why do I get "No supported video media" when I try to access to the file using play.php? Using "mysite.com/Video/test.mp4" I can access directly to the media without problems.

I realized that if I wait a sufficient long time, the browser fully download the file and reproduce it. What I can't obtain is the streaming of the file.

I've found the problem and a possible solution.

  1. The problem is in the fileread, it trasmit the whole file before the browser can process it.
  2. A possible workaround is the use of the X-SendFile module.

In case you use Debian like me is sufficient to:

  • Install it: sudo apt-get install libapache2-mod-xsendfile
  • Modify your site conf (Default path: /ect/apache2/sites-available) adding the following lines at the beginning (or to the chosen VirtualHost):
XSendFile on
XSendFilePath /full/path/to/directory1
XSendFilePath /full/path/to/directory2
  • Restart the web server: sudo systemctl reload apache2 && sudo systemctl restart apache2
  • Update the php script in this way:
$name = "/full/path/to/directory1/".$_GET['req']
header('Accept-Ranges: bytes');
header('Content-Length: ' . filesize($name));
header('Content-Type: ' . mime_content_type($name));
header('Content-Disposition: filename="'.$name.'"');
header('X-Sendfile: $name');

For more information I suggest you to visit this page.