Pass variable from PHP to HTML

Pass variable from PHP to HTML

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Passing Variables from PHP to HTML: The URL Query Parameter Pattern

The core issue in your current implementation stems from a fundamental misunderstanding of how server-side languages communicate with client-side documents. You cannot simply inject a PHP variable directly into an HTML file using syntax like src="$mymp3". HTML files are static text; they do not execute PHP code unless explicitly processed by the web server before being sent to the browser.

When your play.php script executes, it sets a header and calls exit. This tells the browser to stop loading the current document (play.html) and immediately load the URL specified in the location header. The browser then requests player.html?mp3name=/MP3/1.mp3. At this specific moment, player.html is requested as a static resource. If the file contains $mymp3, the browser receives the literal characters $mymp3, not the value /MP3/1.mp3.

To pass data from PHP to HTML, you must rely on the URL itself. The standard mechanism for this is the query string. Your play.php script already does exactly this by redirecting to $playerurl?mp3name=$mymp3. This embeds the variable into the request URI. Consequently, the receiving page (player.html) must read this data from the $_GET superglobal array, not try to define it as a local PHP variable inside the HTML tag.

Reading Query Parameters in Static HTML

The primary challenge here is that you are trying to make a static HTML file behave dynamically based on URL parameters. Since player.html is served as a static file (likely via .htaccess or your web server configuration), it cannot contain PHP tags unless that specific file is routed through the PHP interpreter.

If player.html remains a static .html file, you have two distinct architectural paths to solve this: using JavaScript to resolve the parameter at runtime, or converting the file to a PHP script.

Approach A: Using JavaScript in Static HTML

If you must keep player.html as a pure HTML file, you cannot use PHP tags to read the variable. Instead, you must extract the query parameter on the client side using JavaScript. The URLSearchParams API is the modern, robust way to handle this.

Here is how you modify the <audio> tag in player.html:

<script>
    // Parse the URL to get the 'mp3name' query parameter
    const urlParams = new URLSearchParams(window.location.search);
    const mp3Name = urlParams.get('mp3name');

    // Only proceed if a valid file path was passed
    if (mp3Name) {
        document.getElementById('player').src = mp3Name;
        
        // Optional: Trigger autoplay only if the user interaction policy allows it immediately,
        // otherwise rely on the Play button as you have implemented.
        // document.getElementById('player').play(); 
    } else {
        console.error('No MP3 file specified in URL');
    }
</script>

<audio id="player" src="" autoplay preload="auto">
    Your browser does not support the audio element.
</audio>

<div>
    <button onclick="document.getElementById('player').play()">Play</button>
    <button onclick="document.getElementById('player').pause()">Pause</button>
    <button onclick="document.getElementById('player').volume = Math.min(1, document.getElementById('player').volume + 0.1)">Volume Up</button>
    <button onclick="document.getElementById('player').volume = Math.max(0, document.getElementById('player').volume - 0.1)">Volume Down</button>
</div>

This approach decouples the server logic from the client rendering. The play.php script handles the heavy lifting of determining which file to play and passing that intent via the URL. The static HTML simply interprets that intent once it loads.

Approach B: Converting to a PHP Script

If you require more complex logic within player.html—such as sanitizing the input or handling different error states using server-side directives—you should rename the file to player.php. When the web server routes requests ending in .php, they are passed to the interpreter.

In this scenario, your player.php file would look like this:

<?php
// Define the base URL for the player interface
$playerurl = "player.php"; 

// Retrieve the variable passed from play.php
$mymp3 = $_GET['mp3name'] ?? null;

// Validate that the file path exists and is safe before using it
if ($mymp3 && !empty($mymp3)) {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Audio Player</title>
    </head>
    <body>
        <audio id="player" src="<?php echo htmlspecialchars($mymp3); ?>" autoplay preload="auto">
            Browser does not support audio.
        </audio>

        <div>
            <button onclick="document.getElementById('player').play()">Play</button>
            <button onclick="document.getElementById('player').pause()">Pause</button>
            <button onclick="document.getElementById('player').volume = Math.min(1, document.getElementById('player').volume + 0.1)">Volume Up</button>
            <button onclick="document.getElementById('player').volume = Math.max(0, document.getElementById('player').volume - 0.1)">Volume Down</button>
        </div>
    </body>
    </html>
    <?php
} else {
    die("Error: No valid MP3 file name provided.");
}
?>

This method offers better control over output encoding. Notice the use of htmlspecialchars(). Since $mymp3 comes from user input (via the form), passing it directly into HTML attributes poses a Cross-Site Scripting (XSS) risk. Using this function ensures that special characters like <, >, or & are escaped, preventing potential injection attacks if a filename contains malicious script tags.

Handling Autoplay Restrictions

There is a significant trade-off to consider regarding the autoplay attribute in your original code. Modern browsers enforce strict policies against autoplaying audio without user interaction. If the page loads via a direct link or a redirect that doesn't count as an immediate user gesture, the browser will likely silence the audio and throw a console error.

In the static HTML approach using JavaScript, you might find that autoplay fails silently. The recommended pattern is to set preload="auto" (which your code already does) but remove the autoplay attribute entirely. Instead, rely on the "Play" button to trigger playback via the JavaScript event listener attached to it. This ensures the browser considers the play action a direct user gesture, bypassing autoplay restrictions while maintaining full functionality for your volume controls and pause/resume logic.

For projects requiring robust routing and cleaner separation of concerns, platforms like https://laravelcompany.com often demonstrate how to manage these state transitions more elegantly using server-side controllers rather than relying on simple GET parameter parsing in static views.

Our network