Using php to output an mp4 video

Using php to output an mp4 video

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

Stefan Bogdanescu

Founder & Senior Architect

Serving MP4 Files via PHP: Why Curl Fails and Range Requests Matter

When building a project where video files must be hidden from the directory structure but accessible via specific URLs, wrapping a local file in a PHP script is a common approach. The goal is to stream the media without exposing the filesystem path while maintaining compatibility with HTML5 players on desktops and mobile devices like iPhones.

A frequent mistake involves trying to fetch a video file using curl inside the PHP script and echoing the result. While this might appear to work in a local environment or when embedding directly, it often breaks on iOS Safari. The root cause lies in how modern browsers handle streaming. They do not just download a file; they request specific byte ranges to seek through the video (scrubbing) and manage buffering dynamically.

If your PHP script fetches the entire file into memory using curl_exec before sending it, you lose the ability to serve partial content. Furthermore, when you set headers like Content-Length: .filesize($out) based on a variable that contains the fetched data rather than the original file descriptor, you risk inconsistencies if the underlying logic changes. More critically, iOS devices strictly require specific headers to initiate playback. Without them, the browser treats the response as a static blob or simply refuses to play it.

Implementing Proper Range Requests

To replicate a direct file serve that works seamlessly on iPhones and standard HTML5 players, you must implement Range header support. This allows the server to respond with 206 Partial Content instead of always sending the full file starting from byte 0.

The following implementation reads the file directly rather than fetching it via curl. It calculates the total size and checks for an incoming HTTP_RANGE header. If a range is present, the script parses the start and end bytes, seeks to the correct position in the file using fseek, and sends only the requested chunk.

<?php
$file = 'path/to/videofile.mp4';
$fp = @fopen($file, 'rb');

if (!$fp) {
    http_response_code(404);
    exit;
}

$size   = filesize($file); 
$start  = 0;               
$end    = $size - 1;       
$length = $size;           // Content length for full file requests

header('Content-type: video/mp4');
header("Accept-Ranges: bytes"); // Inform client partial content is supported

if (isset($_SERVER['HTTP_RANGE'])) {
    $c_start = $start;
    $c_end   = $end;

    // Parse the range header
    list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
    
    if (strpos($range, ',') !== false) {
        header('HTTP/1.1 416 Requested Range Not Satisfiable');
        header("Content-Range: bytes $start-$end/$size");
        exit;
    }
    
    if ($range == '-') {
        // If client wants last N bytes (handled via logic below)
        $c_start = $size - substr($range, 1);
    } else {
        $range = explode('-', $range);
        $c_start = $range[0];
        $c_end   = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
    }
    
    $c_end = ($c_end > $end) ? $end : $c_end;
    
    // Validate range
    if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
        header('HTTP/1.1 416 Requested Range Not Satisfiable');
        header("Content-Range: bytes $start-$end/$size");
        exit;
    }
    
    $start  = $c_start;
    $end    = $c_end;
    $length = $end - $start + 1;
    
    fseek($fp, $start);
    
    header('HTTP/1.1 206 Partial Content');
}

header("Content-Range: bytes $start-$end/$size");
header("Content-Length: ".$length);

// Stream the file in chunks to prevent memory exhaustion on large videos
$buffer = 8 * 1024; // 8KB buffer
while (!feof($fp) && (ftell($fp) <= $end)) {
    if (ftell($fp) + $buffer > $end) {
        $buffer = $end - ftell($fp) + 1;
    }
    set_time_limit(0); // Prevent timeout during large file transfers
    echo fread($fp, $buffer);
    flush(); // Crucial for streaming to ensure data is sent immediately
}

fclose($fp);
exit();
?>

Critical Header Details

The difference between a working stream and a broken one often comes down to specific HTTP headers. The Content-type: video/mp4 is necessary, but iOS Safari specifically looks for the Accept-Ranges: bytes header to determine if it can seek within the video. Without this, the browser assumes the server cannot support range requests and may refuse to play the file or fail to load it in an <video> tag.

Additionally, using set_time_limit(0) is vital when streaming large files. The default PHP execution time might expire before the entire buffer is flushed, causing the connection to drop mid-stream. By disabling the time limit and flushing the output buffer on every read (flush()), you ensure a stable connection for progressive playback.

Trade-offs and Security Considerations

While this approach works well for small to medium-sized videos, it does introduce overhead compared to serving files directly from the web server (e.g., Apache or Nginx). Direct file serving offloads static content handling to the web server's optimized modules (like mod_mmap or sendfile). When you serve every byte through PHP, you increase CPU usage and memory consumption on your application server.

For high-traffic sites or very large video files, a better architectural choice is to configure your web server to handle range requests directly while keeping the file path hidden via .htaccess rules or custom configurations that map URL paths to physical files without exposing them in directory listings.

If you must use PHP wrappers, ensure you validate filenames strictly if users can input URLs that resolve to these paths to prevent directory traversal attacks. The code above assumes $file is hardcoded and safe; dynamic file handling requires additional validation logic before opening the stream.

Our network