Skip to content

Commit 52f4df9

Browse files
committed
Fix php-curl-class#322,php-curl-class#369: Add chunked transfer-encoding example
1 parent 956ee3d commit 52f4df9

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

examples/put_large_file_chunked.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
// PUT a file using chunked data.
3+
// See also "examples/receive_large_file_chunked.php".
4+
5+
require __DIR__ . '/vendor/autoload.php';
6+
7+
use \Curl\Curl;
8+
9+
function read_file($ch, $fd, $length) {
10+
$data = fread($fd, $length);
11+
return $data;
12+
}
13+
14+
$filename = 'large_image.png';
15+
$fp = fopen($filename, 'rb');
16+
17+
$curl = new Curl();
18+
$curl->setHeader('Transfer-Encoding', 'chunked');
19+
$curl->setOpt(CURLOPT_UPLOAD, true);
20+
$curl->setOpt(CURLOPT_INFILE, $fp);
21+
$curl->setOpt(CURLOPT_INFILESIZE, filesize($filename));
22+
$curl->setOpt(CURLOPT_READFUNCTION, 'read_file');
23+
$curl->put('http://127.0.0.1:8000/');
24+
25+
fclose($fp);
26+
27+
if ($curl->error) {
28+
echo 'Error: ' . $curl->errorMessage . "\n";
29+
} else {
30+
echo 'Success' . "\n";
31+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
// Receive PUT file.
3+
// See also "examples/put_large_file_chunked.php".
4+
5+
function file_get_contents_chunked($filename, $chunk_size, $callback) {
6+
$handle = fopen($filename, 'r');
7+
while (!feof($handle)) {
8+
call_user_func_array($callback, array(fread($handle, $chunk_size)));
9+
}
10+
fclose($handle);
11+
}
12+
13+
$tmpnam = tempnam('/tmp', 'php-curl-class.');
14+
$file = fopen($tmpnam, 'wb+');
15+
16+
// Use file_get_contents_chunked() rather than file_get_contents() to avoid error:
17+
// "Fatal error: Allowed memory size of ... bytes exhausted (tried to allocate ... bytes) in ... on line 0".
18+
file_get_contents_chunked('php://input', 4096, function($chunk) use (&$file) {
19+
fwrite($file, $chunk);
20+
});

0 commit comments

Comments
 (0)