• Home
  • Guides
    • All
    • Linux
    • Programming
    • Tools
    • WordPress
    Building a Simple WordPress Post List Tool with PHP

    Building a Simple WordPress Post List Tool with PHP

    Monitoring Web Page Changes with Python

    Monitoring Web Page Changes with Python

    My SSH Setup: How I Manage Multiple Servers

    My SSH Setup: How I Manage Multiple Servers

    Building a Network Tracker Auditor for Privacy with Python

    Building a Network Tracker Auditor for Privacy with Python

    Streaming Audio Files Securely with PHP

    Streaming Audio Files Securely with PHP

    Scraping Web Data with Python Helium

    Scraping Web Data with Python Helium

    Building a Secure 2FA Authenticator with Python

    Building a Secure 2FA Authenticator with Python

    Building a Cache Warmer with Python

    Building a Cache Warmer with Python

    How to Create a Python GUI to Launch Webhooks

    How to Create a Python GUI to Launch Webhooks

  • Blog
    • All
    • Artificial Intelligence
    • Privacy
    • Reviews
    • Security
    • Tutorials
    Why Stable Websites Outperform Flashy Redesigns

    Why Stable Websites Outperform Flashy Redesigns

    AdGuard Ad Blocker Review

    AdGuard Ad Blocker Review

    Surfshark VPN Review

    Surfshark VPN Review

    Nmap Unleash the Power of Cybersecurity Scanning

    Nmap: Unleash the Power of Cybersecurity Scanning

    Floorp Browser Review

    Floorp Browser Review

    Understanding Man-in-the-Middle Attacks

    Understanding Man-in-the-Middle Attacks

    Privacy-Focused Analytics

    Privacy-Focused Analytics: Balancing Insights and Integrity

    Safeguarding Your Facebook Account

    Safeguarding Your Facebook Account: Understanding the Differences Between Hacking and Cloning

    38 essential points to harden WordPress

    38 Essential Points to Harden WordPress

  • Apps
    • Bible App
    • Bible Verse Screensaver
    • Blue AI Chatbot
    • Early Spring Predictor
    • FIGlet Generator
    • Password Generator
    • StegX
    • The Matrix
    • WeatherX
    • Website Risk Level Tool
  • About
    • About JMooreWV
    • Live Cyber Attacks
  • Contact
    • General Contact
    • Website Administration & Cybersecurity
No Result
View All Result
  • Home
  • Guides
    • All
    • Linux
    • Programming
    • Tools
    • WordPress
    Building a Simple WordPress Post List Tool with PHP

    Building a Simple WordPress Post List Tool with PHP

    Monitoring Web Page Changes with Python

    Monitoring Web Page Changes with Python

    My SSH Setup: How I Manage Multiple Servers

    My SSH Setup: How I Manage Multiple Servers

    Building a Network Tracker Auditor for Privacy with Python

    Building a Network Tracker Auditor for Privacy with Python

    Streaming Audio Files Securely with PHP

    Streaming Audio Files Securely with PHP

    Scraping Web Data with Python Helium

    Scraping Web Data with Python Helium

    Building a Secure 2FA Authenticator with Python

    Building a Secure 2FA Authenticator with Python

    Building a Cache Warmer with Python

    Building a Cache Warmer with Python

    How to Create a Python GUI to Launch Webhooks

    How to Create a Python GUI to Launch Webhooks

  • Blog
    • All
    • Artificial Intelligence
    • Privacy
    • Reviews
    • Security
    • Tutorials
    Why Stable Websites Outperform Flashy Redesigns

    Why Stable Websites Outperform Flashy Redesigns

    AdGuard Ad Blocker Review

    AdGuard Ad Blocker Review

    Surfshark VPN Review

    Surfshark VPN Review

    Nmap Unleash the Power of Cybersecurity Scanning

    Nmap: Unleash the Power of Cybersecurity Scanning

    Floorp Browser Review

    Floorp Browser Review

    Understanding Man-in-the-Middle Attacks

    Understanding Man-in-the-Middle Attacks

    Privacy-Focused Analytics

    Privacy-Focused Analytics: Balancing Insights and Integrity

    Safeguarding Your Facebook Account

    Safeguarding Your Facebook Account: Understanding the Differences Between Hacking and Cloning

    38 essential points to harden WordPress

    38 Essential Points to Harden WordPress

  • Apps
    • Bible App
    • Bible Verse Screensaver
    • Blue AI Chatbot
    • Early Spring Predictor
    • FIGlet Generator
    • Password Generator
    • StegX
    • The Matrix
    • WeatherX
    • Website Risk Level Tool
  • About
    • About JMooreWV
    • Live Cyber Attacks
  • Contact
    • General Contact
    • Website Administration & Cybersecurity
No Result
View All Result
Home Guides Programming PHP

Streaming Audio Files Securely with PHP

Jonathan Moore by Jonathan Moore
1 year ago
Reading Time: 5 mins read
A A
Streaming Audio Files Securely with PHP
FacebookTwitter

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:

  1. 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.
  2. 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.

Tags: MP3PHPSecurityStreaming
ShareTweetSharePinShareShareScan
ADVERTISEMENT
Jonathan Moore

Jonathan Moore

Senior Software Engineer and Cybersecurity Specialist with over 3 decades of experience in developing web, desktop, and server applications for Linux and Windows-based operating systems. Worked on numerous projects, including automation, artificial intelligence, data analysis, application programming interfaces, intrusion detection systems, streaming audio servers, WordPress plugins, and much more.

Related Articles

Building a Simple WordPress Post List Tool with PHP

Building a Simple WordPress Post List Tool with PHP

I needed a quick way to view all my WordPress posts without logging into the admin dashboard. Sometimes you just...

Why Stable Websites Outperform Flashy Redesigns

Why Stable Websites Outperform Flashy Redesigns

Most websites do not fail in dramatic fashion. There is no explosion, no warning siren, no obvious moment where everything...

AdGuard Ad Blocker Review

AdGuard Ad Blocker Review

Ad blocking software has become essential for anyone who values a clean, fast, and secure browsing experience. With the ever-increasing...

Next Post
Surfshark VPN Review

Surfshark VPN Review

Recommended Services

Latest Articles

Building a Simple WordPress Post List Tool with PHP

Building a Simple WordPress Post List Tool with PHP

I needed a quick way to view all my WordPress posts without logging into the admin dashboard. Sometimes you just...

Read moreDetails

Why Stable Websites Outperform Flashy Redesigns

Why Stable Websites Outperform Flashy Redesigns

Most websites do not fail in dramatic fashion. There is no explosion, no warning siren, no obvious moment where everything...

Read moreDetails

Monitoring Web Page Changes with Python

Monitoring Web Page Changes with Python

There are times when I need to know that a web page has changed without actively watching it. That might...

Read moreDetails

My SSH Setup: How I Manage Multiple Servers

My SSH Setup: How I Manage Multiple Servers

If you work with more than one server, the need to manage multiple servers with SSH becomes obvious pretty quickly....

Read moreDetails
  • Privacy Policy
  • Terms of Service

© 2025 JMooreWV. All rights reserved.

No Result
View All Result
  • Home
  • Guides
    • Linux
    • Programming
      • JavaScript
      • PHP
      • Python
    • Tools
    • WordPress
  • Blog
    • Artificial Intelligence
    • Tutorials
    • Privacy
    • Security
  • Apps
    • Bible App
    • Bible Verse Screensaver
    • Blue AI Chatbot
    • Early Spring Predictor
    • FIGlet Generator
    • Password Generator
    • StegX
    • The Matrix
    • WeatherX
    • Website Risk Level Tool
  • About
    • About JMooreWV
    • Live Cyber Attacks
  • Contact
    • General Contact
    • Website Administration & Cybersecurity