As you said you use Apache, it has a very interesting tool to send files under PHP control, but at the same time without needing PHP to generate communication, which is the module x-sendfile
.
http://blog.jasny.net/articles/how-i-php-x-sendfile/
This module allows you to return control of the connection to Apache, indicating a file to be served, and for this, just set a header:
X-Sendfile: /caminho
I assume you already have some way to authenticate the user. Assuming he is allowed to view the videos, one possibility is to record a token in a session, and validate in this way:
listavideos.php
<?php
// estou supondo que você autenticou o usuário,
// e criou um token único, aleatório e complexo
// para ele em $_SESSION['token']
session_start();
...
echo '<source src="/show.php?token='.$_SESSION['token'].'&video=23" type="video/mp4">';
And in show.php:
session_start();
if( $_GET['token'] == $_SESSION['token'] ) {
header( 'Content-type: video/mp4' );
// aqui vai o caminho real para o vídeo, que não aparecerá para
// o usuário final. Sugiro fazer um sistema mais complexo que
// este do exemplo, usar um hash para o nome real do video,
// ou mesmo colocar os vídeos num lugar inacessível para uso
// "direto".
header( 'X-Sendfile: /videos/caminhocomplexo/'.$video.'.mp4' );
die();
} else {
echo 'Link inválido';
die();
}
Of course I simplified the code to illustrate, but the basic idea is this. Obviously, later you can do more by making the URL friendly (for example, passing the data in the URL path and not in the query string, but there is already "improvement").
Sending without X-Sendfile
Using the same logic from above, we can exchange the header X-Sendfile
therefore:
readfile( '/videos/caminhocomplexo/'.$video.'.mp4' );
Only you need to keep in mind that this causes that during the whole sending of the data, the PHP process will be running, and this can cause a timeout
in most of the accommodations.
Additionally, if it is a stream long, would need to give a support to ranges, that is, allow some customer to start reading the video medium data, for example.
PHP allows setting the execution time of a script, but it can never exceed the maximum set in PHP.ini
, which is often not accessible by the hosting client.
The first step is not to point the URL to the actual video path. Which http server is used?
– Bacco
The server is Apache
– Gabriela Mombak
apache has a module called x-sendfile, very useful for these cases. If you point the URL to a PHP that validates a cookie, and use a
header("X-Sendfile: /caminho/correto/paraovideo.mp4");
, the person receives the data without knowing the original path. You can do without this module, but then the entire stream has to go through PHP processing, which is not always desirable. Another advantage of x-sendfile is that it supports ranges, what is desirable for streaming videos.– Bacco
OK thank you so much, I will study the x-sendfile. You could put as answer this comment?
– Gabriela Mombak