Breaking News
Home / Web / PHP / PHP Snippets / How do you serve a image file using PHP?

How do you serve a image file using PHP?

Code Snippet

Lets say you have to build and image server using PHP. The image filename to be severed is specified with the file GET parameter and this script is called as get-image.php which is located in the root of your website.

e.g. http://yoursite.com/get-image.php?file=logo.png

The following snippet reads the file content and outputs it to the stream.

  1. <?php
  2.  
  3. // basic headers
  4. header("Content-type: image/png");
  5. header("Expires: Mon, 1 Jan 2099 05:00:00 GMT");
  6. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  7. header("Cache-Control: no-store, no-cache, must-revalidate");
  8. header("Cache-Control: post-check=0, pre-check=0", false);
  9. header("Pragma: no-cache");
  10.  
  11. // get the file name
  12. $file=@$_GET[‘file’];
  13.  
  14. // get the size for content length
  15. $size= filesize($file);
  16. header("Content-Length: $size bytes");
  17.  
  18. // output the file contents
  19. readfile($file);
  20.  
  21. ?>

<!>

[pb_builder]

Check Also

How to list files in a directory in PHP?

<?php if ($handle = opendir(‘/path/to/directory’)) {     echo "Directory handle: $handlen";     echo …

Advertisment ad adsense adlogger