422,530 Members | 1,144 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 422,530 IT Pros & Developers. It's quick & easy.

How we can serve pdf using range header in php?

P: 1
Hello,
Can anyone provide any Pdf byte serving example because people are talking about that but no one is providing solution ,I had tried with range header which I had previously used for video streaming but it is not working.

Can anyone please help me about "How we can serve pdf" using range header?
Jan 4 '18 #1
Share this Question
Share on Google+
1 Reply


Expert 100+
P: 921
Adapt as needed the following:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. $file = "test.pdf";
  3. $fp = @fopen($file, 'rb');
  4. $size   = filesize($file); // File size
  5. $length = $size;           // Content length
  6. $start  = 0;               // Start byte
  7. $end    = $size - 1;       // End byte
  8.  
  9. header('Content-type: application/pdf');
  10. header("Accept-Ranges: bytes");
  11.  
  12. if (isset($_SERVER['HTTP_RANGE'])) {
  13.     $c_start = $start;
  14.     $c_end   = $end;
  15.  
  16.     list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
  17.     if (strpos($range, ',') !== false) {
  18.         header('HTTP/1.1 416 Requested Range Not Satisfiable');
  19.         header("Content-Range: bytes $start-$end/$size");
  20.         exit;
  21.     }
  22.     if ($range == '-') {
  23.         $c_start = $size - substr($range, 1);
  24.     }else{
  25.         $range  = explode('-', $range);
  26.         $c_start = $range[0];
  27.         $c_end   = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
  28.     }
  29.     $c_end = ($c_end > $end) ? $end : $c_end;
  30.     if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
  31.         header('HTTP/1.1 416 Requested Range Not Satisfiable');
  32.         header("Content-Range: bytes $start-$end/$size");
  33.         exit;
  34.     }
  35.     $start  = $c_start;
  36.     $end    = $c_end;
  37.     $length = $end - $start + 1;
  38.     fseek($fp, $start);
  39.     header('HTTP/1.1 206 Partial Content');
  40. }
  41.  
  42. header("Content-Range: bytes $start-$end/$size");
  43. header("Content-Length: ".$length);
  44.  
  45.  
  46. $buffer = 1024 * 8;
  47. while(!feof($fp) && ($p = ftell($fp)) <= $end) {
  48.  
  49.     if ($p + $buffer > $end) {
  50.         $buffer = $end - $p + 1;
  51.     }
  52.     set_time_limit(0);
  53.     echo fread($fp, $buffer);
  54.     flush();
  55. }
  56.  
  57. fclose($fp);
  58.  
Jan 6 '18 #2

Post your reply

Sign in to post your reply or Sign up for a free account.