PHP is widely used for managing file access, handling data securely, and serving multimedia content online. One of the common use cases is audio streaming, especially for websites offering protected audio content. Streaming audio files using PHP not only provides flexibility in how files are served but also allows added control over access and file management. In this guide, we’ll cover a PHP script that securely streams audio files, restricts access by referrer, and supports partial content delivery, making it ideal for situations where audio content needs to be streamed directly to users’ browsers.
Why This Code is Useful
Streaming audio content securely is essential for many websites. Whether you’re hosting educational material, podcasts, or licensed music, providing access to these files without sacrificing security or user experience is important. The PHP code we’ll explore here is designed to handle several key needs:
- Access Restriction: It restricts file access based on the referring domain, ensuring that only requests originating from allowed sites can access your audio files. This prevents unauthorized embedding or linking to your audio content from other sites.
- Partial Content Support: This feature is beneficial for streaming, as it allows users to seek to different parts of an audio file. Browsers use HTTP range headers to request specific byte ranges, and this script is equipped to handle those requests, providing smooth playback without re-downloading the entire file.
With these features, the PHP script provides both secure access and a smooth user experience, making it a reliable solution for hosting audio content online.
Full PHP Code
Here’s the complete PHP script used for secure audio streaming:
<?php // Define allowed referrers for access restriction $allowed_referrers = [ 'https://yourdomain.com/', 'https://anotherdomain.com/' ]; // Retrieve the 'file' parameter from the URL, defaulting to an empty string if not provided $file = $_GET[ 'file' ] ?? ''; // Check if a file was provided in the URL if ( !empty( $file ) ) { // Sanitize file name to prevent directory traversal attacks // This ensures only the base filename is used without any path components $file = basename( str_replace( '..', '', $file ) ); // Define the path to the audio file $path = __DIR__ . "/audio/" . $file; // Check if the request comes from an allowed referrer $is_allowed_referrer = false; foreach ( $allowed_referrers as $referrer ) { if ( strpos( $_SERVER[ 'HTTP_REFERER' ], $referrer ) === 0 ) { $is_allowed_referrer = true; break; } } // If the referrer is allowed, and the file exists and is readable if ( $is_allowed_referrer && file_exists( $path ) && is_readable( $path ) ) { // Get the file size and set default range values $size = filesize( $path ); $start = 0; $length = $size; // Check if there is a range header for partial content requests (for streaming) if ( isset( $_SERVER[ 'HTTP_RANGE' ] ) ) { // Parse the range header to get the start and end bytes $range = $_SERVER[ 'HTTP_RANGE' ]; list( , $range ) = explode( '=', $range, 2 ); list( $start, $end ) = explode( '-', $range ); // Set start and end positions for the requested range $start = intval( $start ); $end = ( $end === '' ) ? ( $size - 1 ) : intval( $end ); $length = $end - $start + 1; // Send partial content headers for range requests header( 'HTTP/1.1 206 Partial Content' ); header( "Content-Range: bytes $start-$end/$size" ); } else { // Send standard 200 OK header if full content is requested header( 'HTTP/1.1 200 OK' ); } // Set headers to specify content type and file metadata header( 'Content-Type: audio/mpeg' ); header( 'Content-Disposition: inline; filename="' . basename( $path ) . '"' ); header( 'Content-Length: ' . $length ); header( 'Accept-Ranges: bytes' ); // Open the file, move to the requested start byte, and output the data $file = fopen( $path, 'rb' ); fseek( $file, $start ); echo fread( $file, $length ); fclose( $file ); exit; // Exit script after outputting the file } else { // Send 404 Not Found if file does not exist or access is restricted header( "HTTP/1.0 404 Not Found" ); echo "Audio file not found or access is restricted."; exit; } } else { // Send 403 Forbidden if no file parameter is provided header( "HTTP/1.0 403 Forbidden" ); echo "Access denied."; exit; }
How to Use the Code
To stream audio using this PHP script, you can use the following HTML code. The <audio> element provides user controls for playback, and the controlsList=”nodownload” attribute prevents file downloads from the browser’s UI.
<audio controls controlsList="nodownload" oncontextmenu="return false;" preload="auto"> <source src="https://yourdomain.com/path_to_script.php?file=sample.mp3" type="audio/mpeg"> Your browser does not support the audio element. </audio>
This code embeds an audio player on your webpage that plays the specified audio file (sample.mp3). By linking the src attribute to the PHP script, you’re ensuring that only requests originating from your allowed referrers can access the audio content. Additionally, the oncontextmenu=”return false;” attribute disables the right-click menu on the audio element to deter users from attempting to download the file.
Code Breakdown
Let’s examine the PHP script to understand how each part functions:
Allowed Referrer Configuration:
$allowed_referrers = [ 'https://yourdomain.com/', 'https://anotherdomain.com/' ];
Here, you define which domains are allowed to access the audio content. This restriction is checked later in the code to ensure requests originate from trusted sources.
Retrieving and Validating the File Parameter:
$file = $_GET[ 'file' ] ?? '';
This retrieves the file parameter from the URL. If no parameter is provided, $file defaults to an empty string.
File Name Sanitization:
$file = basename( str_replace( '..', '', $file ) );
This line removes any directory traversal patterns (..) and keeps only the file name’s base to prevent unauthorized access to other directories.
File Path Definition:
$path = __DIR__ . "/audio/" . $file;
Defines the path to the audio file within an audio directory. This path is later used to verify file existence and access permissions.
Referrer Validation:
foreach ( $allowed_referrers as $referrer ) { if ( strpos( $_SERVER[ 'HTTP_REFERER' ], $referrer ) === 0 ) { $is_allowed_referrer = true; break; } }
This section loops through allowed referrers to verify if the request’s referrer is listed. If an allowed referrer is found, access continues; otherwise, it’s denied.
Partial Content Handling:
if ( isset( $_SERVER[ 'HTTP_RANGE' ] ) ) { $range = $_SERVER[ 'HTTP_RANGE' ]; list( , $range ) = explode( '=', $range, 2 ); list( $start, $end ) = explode( '-', $range ); $start = intval( $start ); $end = ( $end === '' ) ? ( $size - 1 ) : intval( $end ); $length = $end - $start + 1; header( 'HTTP/1.1 206 Partial Content' ); header( "Content-Range: bytes $start-$end/$size" ); } else { header( 'HTTP/1.1 200 OK' ); }
This code block checks for a Range header, which indicates a partial content request. If found, it calculates the requested byte range and sends partial content headers to enable streaming.
Headers for File Output:
header( 'Content-Type: audio/mpeg' ); header( 'Content-Disposition: inline; filename="' . basename( $path ) . '"' ); header( 'Content-Length: ' . $length ); header( 'Accept-Ranges: bytes' );
Sets headers to specify the file’s MIME type and disposition, ensuring it’s handled as an audio file. The Content-Disposition header forces inline display, preventing download prompts.
File Output and Cleanup:
$file = fopen( $path, 'rb' ); fseek( $file, $start ); echo fread( $file, $length ); fclose( $file ); exit;
Opens the file in read-binary mode, moves to the requested byte, reads the appropriate content length, and outputs it directly. Finally, it closes the file and exits to prevent further script execution.
Error Handling: If the file or access criteria are invalid, HTTP headers like 404 Not Found or 403 Forbidden are returned, alerting users to the issue.
Conclusion
This PHP script provides a practical solution for securely streaming audio files while protecting content access through referrer validation and range support. Its straightforward approach to managing requests and handling partial content makes it a great tool for delivering audio content on the web without sacrificing security or user experience. By following this guide, you can effectively integrate secure audio streaming on your website and customize it further based on your unique requirements.