Fix #322,#369: Add chunked transfer-encoding example

This commit is contained in:
Zach Borboa
2016-09-12 02:16:21 -07:00
parent 956ee3d23d
commit 52f4df9cfe
2 changed files with 51 additions and 0 deletions
+31
View File
@@ -0,0 +1,31 @@
<?php
// PUT a file using chunked data.
// See also "examples/receive_large_file_chunked.php".
require __DIR__ . '/vendor/autoload.php';
use \Curl\Curl;
function read_file($ch, $fd, $length) {
$data = fread($fd, $length);
return $data;
}
$filename = 'large_image.png';
$fp = fopen($filename, 'rb');
$curl = new Curl();
$curl->setHeader('Transfer-Encoding', 'chunked');
$curl->setOpt(CURLOPT_UPLOAD, true);
$curl->setOpt(CURLOPT_INFILE, $fp);
$curl->setOpt(CURLOPT_INFILESIZE, filesize($filename));
$curl->setOpt(CURLOPT_READFUNCTION, 'read_file');
$curl->put('http://127.0.0.1:8000/');
fclose($fp);
if ($curl->error) {
echo 'Error: ' . $curl->errorMessage . "\n";
} else {
echo 'Success' . "\n";
}
+20
View File
@@ -0,0 +1,20 @@
<?php
// Receive PUT file.
// See also "examples/put_large_file_chunked.php".
function file_get_contents_chunked($filename, $chunk_size, $callback) {
$handle = fopen($filename, 'r');
while (!feof($handle)) {
call_user_func_array($callback, array(fread($handle, $chunk_size)));
}
fclose($handle);
}
$tmpnam = tempnam('/tmp', 'php-curl-class.');
$file = fopen($tmpnam, 'wb+');
// Use file_get_contents_chunked() rather than file_get_contents() to avoid error:
// "Fatal error: Allowed memory size of ... bytes exhausted (tried to allocate ... bytes) in ... on line 0".
file_get_contents_chunked('php://input', 4096, function($chunk) use (&$file) {
fwrite($file, $chunk);
});