mirror of
https://github.com/php-curl-class/php-curl-class.git
synced 2026-08-30 12:14:36 +00:00
Fix #322,#369: Add chunked transfer-encoding example
This commit is contained in:
@@ -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";
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
Reference in New Issue
Block a user