cURL / Mailing Lists / curl-and-php / Single Mail

curl-and-php

Re: Server memory usage

From: haroon ahmad <haroon_at_fastcreators.com>
Date: Sun, 8 Feb 2009 09:42:51 +0000

there is a definite need to handle buffering through PHP and it is not the
default behavior of your webserver. You have to control it from PHP
otherwise webserver / apache will compile all the code and then send the
output to the browser.

So sticking to PHP to handle downloading large files, here is my solution
that works for me,

<?php
  define('CHUNK_SIZE', 1024*1024); // Size (in bytes) of tiles chunk

  // Read a file and display its content chunk by chunk
  function readfile_chunked($filename, $retbytes = TRUE) {
    $buffer = '';
    $cnt =0;
    // $handle = fopen($filename, 'rb');
    $handle = fopen($filename, 'rb');
    if ($handle === false) {
      return false;
    }
    while (!feof($handle)) {
      $buffer = fread($handle, CHUNK_SIZE);
      echo $buffer;
      ob_flush();
      flush();
      if ($retbytes) {
        $cnt += strlen($buffer);
      }
    }
    $status = fclose($handle);
    if ($retbytes && $status) {
      return $cnt; // return num. bytes delivered like readfile() does.
    }
    return $status;
  }

  // Here goes your code for checking that the user is logged in
  // ...
  // ...

  if ($logged_in) {
    $filename = 'path/to/your/file';
    $mimetype = 'mime/type';
    header('Content-Type: '.$mimetype );
    readfile_chunked($filename);
  }
  else {
    echo 'permission denied.';
  }
?>

the technique is to use readfile_chunked() php function, you can read the
php manual for further information. Also make sure your Apache version is >
1.3 as former versions were bad in handling buffering. HTH

Regards,
Haroon Ahmad
PHP Developer UK
www.haroonahmad.co.uk

_______________________________________________
http://cool.haxx.se/cgi-bin/mailman/listinfo/curl-and-php
Received on 2009-02-08