Menü schliessen
Created: January 5th 2024
Last updated: March 16th 2024
Categories: Common Web Development,  Php
Author: Tim Fürer

PHP: How to serve file as response

Tags:  function,  guide,  PHP
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

In this short article, we'll show how to serve files as responses in PHP.


How To

<?php

$file = 'path/to/file';

$resource_content = file_get_contents($file);
$mime_type = mime_content_type($file);
$content_length = strlen($resource_content);

header("Content-type: {$mime_type};");
header("Content-Length:  {$content_length};");

echo $resource_content;

?>

 

  1. $file: This variable stores the path to the file that we want to serve.
  2. file_get_contents(): This PHP function reads the entire file into a string. It takes the file path as an argument and returns its contents.
  3. mime_content_type(): This function determines the MIME type of the file. MIME types are used to identify the type of content being served. It helps the browser to handle the content appropriately.
  4. strlen(): Calculates the length of the file content. This is used to set the Content-Length header, which informs the client (browser) about the size of the response.
  5. header(): This function is used to send HTTP headers to the client. In this code, it sets the Content-type and Content-Length headers based on the file type and content length.
  6. echo $resource_content: Finally, the file content is echoed back to the client, effectively serving the file as a response.