I am playing an audio in mp3 format and video in mp4 format but want to hide the URL using PHP.I followed this PHP: How can I block direct URL access to a file, but still allow it to be downloaded by logged in users?.
HTML Code
<audio controls>
<source src="get_song.php?name=my-song-name" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<video controls>
<source src="get_video.php?name=my-video-name" type="video/mp4">
Your browser does not support the video element.
</video>
PHP
get_song.php
if( !empty( $_GET['name'] ) )
{
// check if user is logged
if( is_logged() )
{
$song_name = preg_replace( '#[^-\w]#', '', $_GET['name'] );
$song_file = "
{$_SERVER['DOCUMENT_ROOT']}/members/files/{$song_name}.mp3";
if( file_exists( $song_file ) )
{
header( 'Cache-Control: public' );
header( 'Content-Description: File Transfer' );
header( "Content-Disposition: attachment; filename={$song_file}" );
header( 'Content-Type: application/mp3' );
header( 'Content-Transfer-Encoding: binary' );
readfile( $song_file );
exit;
}
}
}
die( "ERROR: invalid song or you don't have permissions to download it." );
get_video.php
if( !empty( $_GET['name'] ) )
{
// check if user is logged
if( is_logged() )
{
$video_name = preg_replace( '#[^-\w]#', '', $_GET['name'] );
$video_file = "
{$_SERVER['DOCUMENT_ROOT']}/members/files/{$video_name}.mp4";
if( file_exists( $song_file ) )
{
header( 'Cache-Control: public' );
header( 'Content-Description: File Transfer' );
header( "Content-Disposition: attachment; filename={$video_file}" );
header( 'Content-Type: application/mp4' );
header( 'Content-Transfer-Encoding: binary' );
readfile( $video_file );
exit;
}
}
}
die( "ERROR: invalid song or you don't have permissions to download it." );
But the problem is it takes a lot of time for the audio to stream and gets cut in the middle and loop back from the beginning. Also, the video is not loading on mobile. Is there something wrong with the headers? what is the correct headers for this?
I found another solution here but still the video is not loading and audio is looping back. Hide audio url in PHP:
$filename = '/path/to/audio.mp3';
if(is_file($filename))
{
header('Content-Type: audio/mpeg');
header('Content-Disposition:
inline;filename="'.basename($filename).'"');
header('Content-length: '.filesize($filename));
header('Cache-Control: no-cache');
header("Content-Transfer-Encoding: chunked");
readfile($filename);
}
$videoname = '/path/to/video.mp4';
if(is_file($videoname))
{
header('Content-Type: video/mp4');
header('Content-Disposition:
inline;filename="'.basename($videoname).'"');
header('Content-length: '.filesize($videoname));
header('Cache-Control: no-cache');
header("Content-Transfer-Encoding: chunked");
readfile($videoname);
}
What is the difference between content transfer encoding Chunked and Binary? What are the correct headers for audio and video?