Jump to content

cURL Byte Range Alternative


mattal999

Recommended Posts

Hi Guys,

 

I have this function, which connects to a file, retrieves the first 64kb (roughly) and the last 64kb (again, roughly). Now my problem is that when I run it I get an error that my server doesn't support byte ranges in cURL. Great. So I need an alternative. Code below:

 

<?php

function transfer_id3_header_and_footer($ch, $url, $file, $size = 0) {
  if (!$fp = fopen($file, "wb")) {
    echo 'Error opening temp file for binary writing.<br /><br />';
    return false;
  } else if (!$urlp = fopen($url, "r")) {
    echo 'Error opening URL for reading<br /><br />';
    return false;
  }

  try {
    $to_get = 65536; // 64 KB
    $chunk_size = 4096; // Haven't bothered to tune this, maybe other values would work better??
    $got = 0; $data = null;
    
    // Grab the first 64 KB of the file
    while(!feof($urlp) && $got < $to_get) {
      $data = $data . fgets($urlp, $chunk_size);
      $got += $chunk_size;
    }
    fwrite($fp, $data);
    
    // Grab the last 64 KB of the file, if we know how big it is.
    if ($size > 0) {
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_FILE, $fp);
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLOPT_RESUME_FROM, $size - $to_get);
      if(curl_exec($ch) === false) {
        die(curl_error($ch));
      }
    }

    // Now $fp should be the first and last 64KB of the file!!

    fclose($fp);
    fclose($urlp);
  } catch (Exception $e) {
    fclose($fp);
    fclose($urlp);
    echo 'Error transfering file using fopen and cURL.<br /><br />';
    return false;
  }

  return true;
}

$ch = curl_init();
$url = $mp3['url']; // I have these set up properly in the real thing, this is just to show variables are being set.
$file = rand()."22.mp3";
$size = getSizeFile($url); // This is my own function that is not shown.
transfer_id3_header_and_footer($ch, $url, $file, $size);

?>

 

I get this error (sometimes, not always):

 

The server does not support or accept range requests. Could not resume.

 

Side note: While I was writing this, the error seems to have disappeared. However, I am still unsure weather it is working as it should. The question still stands. Are there any alternatives?

Link to comment
https://forums.phpfreaks.com/topic/164577-curl-byte-range-alternative/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.