良いオプションが見つからなかったので、私はfsockopen
という既定の解決策に行きました。
ここでは、メモリ消費量の少ないHTTP要求を実行するユーティリティ関数の完全なソースコードを示します。 data
パラメータとして、string
,array
およびSplFileInfo
オブジェクトを受け入れることができます。
/**
* Performs memory-safe HTTP request.
*
* @param string $url Request URL, e.g. "https://example.com:23986/api/upload".
* @param string $method Request method, e.g. "GET", "POST", "PATCH", etc.
* @param mixed $data [optional] Data to pass with the request.
* @param array $headers [optional] Additional headers.
*
* @return string Response body.
*
* @throws Exception
*/
function request($url, $method, $data = null, array &$headers = []) {
static $schemes = [
'https' => ['ssl://', 443],
'http' => ['', 80],
];
$u = parse_url($url);
if (!isset($u['host']) || !isset($u['scheme']) || !isset($schemes[$u['scheme']])) {
throw new Exception('URL parameter must be a valid URL.');
}
$scheme = $schemes[$u['scheme']];
if (isset($u['port'])) {
$scheme[1] = $u['port'];
}
$fp = @fsockopen($scheme[0] . $u['host'], $scheme[1], $errno, $errstr);
if ($fp === false) {
throw new Exception($errstr, $errno);
}
$uri = isset($u['path']) ? $u['path'] : '/';
if (isset($u['query'])) {
$uri .= '?' . $u['query'];
}
if (is_array($data)) {
$data = http_build_query($data);
$headers['Content-Type'] = 'application/x-www-form-urlencoded';
$headers['Content-Length'] = strlen($data);
} elseif ($data instanceof SplFileInfo) {
$headers['Content-Length'] = $data->getSize();
}
$headers['Host'] = $this->host;
$headers['Connection'] = 'close';
fwrite($fp, sprintf("%s /api%s HTTP/1.1\r\n", $method, $uri));
foreach ($headers as $header => $value) {
fwrite($fp, $header . ': ' . $value . "\r\n");
}
fwrite($fp, "\r\n");
if ($data instanceof SplFileInfo) {
$fh = fopen($data->getPathname(), 'rb');
while ($chunk = fread($fh, 4096)) {
fwrite($fp, $chunk);
}
fclose($fh);
} else {
fwrite($fp, $data);
}
$response = '';
while (!feof($fp)) {
$response .= fread($fp, 1024);
}
fclose($fp);
if (false === $pos = strpos($response, "\r\n\r\n")) {
throw new Exception('Bad server response body.');
}
$headers = explode("\r\n", substr($response, 0, $pos));
if (!isset($headers[0]) || strpos($headers[0], 'HTTP/1.1 ')) {
throw new Exception('Bad server response headers.');
}
return substr($response, $pos + 4);
}
使用例:
$file = new SplFileObject('/path/to/file', 'rb');
$contents = request('https://example.com/api/upload', 'POST', $file, $headers);
if ($headers[0] == 'HTTP/1.1 200 OK') {
print $contents;
}
は、ストリームをオープンし、そのストリームに小さなチャンクでファイルを養います。 –
ftpを使用できませんか? –
@MarcBこれを 'stream_context_create(['http'])'と組み合わせて、送信/解析ヘッダなどでプロトコルを再実装することはできませんか? – VisioN