6

有没有办法

curl -X POST -H "Content-Type:application/xml" --data @myfile.xml http://example.com

但直接在PHP中?

CURLOPT_PUT/CURLOPT_UPLOAD以及file_get_contents以及exec

不是解决方案,因为它必须是 POST 并且文件很大,因此必须流式传输。

有任何想法吗?

4

2 回答 2

14

我在尝试将大量摄取文件从 PHP 提供给 elasticsearch 的批量 API 时遇到了类似的问题,直到我意识到批量 API 端点接受了 PUT 请求。无论如何,这段代码使用大文件执行 POST 请求:

$curl = curl_init();
curl_setopt( $curl, CURLOPT_PUT, 1 );
curl_setopt( $curl, CURLOPT_INFILESIZE, filesize($tmpFile) );
curl_setopt( $curl, CURLOPT_INFILE, ($in=fopen($tmpFile, 'r')) );
curl_setopt( $curl, CURLOPT_CUSTOMREQUEST, 'POST' );
curl_setopt( $curl, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json' ] );
curl_setopt( $curl, CURLOPT_URL, $url );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
$result = curl_exec($curl);
curl_close($curl);
fclose($in);

这里,$tmpFile是包含请求正文的文件的完整路径。

注意:重要的部分是设置CURLOPT_CUSTOMREQUEST'POST'即使CURLOPT_PUT已设置。

您必须使Content-Type:标头适应服务器的期望。

使用 tcpdump,我可以确认请求方法是 POST:

POST /my_index/_bulk HTTP/1.1
Host: 127.0.0.1:9200
Accept: */*
Content-Type: application/json
Content-Length: 167401
Expect: 100-continue

[...snip...]

我在 Ubuntu 14.04 上使用软件包 libcurl3(版本 7.35.0-1ubuntu2.5)和 php5-curl(版本 5.5.9+dfsg-1ubuntu4.11)。

于 2015-07-29T09:44:47.867 回答
1

Curl 支持 post,所以我相信您正在寻找这样的东西:Posting or Uploading Files Using Curl With PHP

// URL on which we have to post data
$url = "http://localhost/tutorials/post_action.php";
// Any other field you might want to catch
$post_data['name'] = "khan";
// File you want to upload/post
$post_data['file'] = "@c:/logs.log";

// Initialize cURL
$ch = curl_init();
// Set URL on which you want to post the Form and/or data
curl_setopt($ch, CURLOPT_URL, $url);
// Data+Files to be posted
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
// Pass TRUE or 1 if you want to wait for and catch the response against the request made
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// For Debug mode; shows up any error encountered during the operation
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Execute the request
$response = curl_exec($ch);

// Just for debug: to see response
echo $response;

(代码的所有功劳归于原始链接作者)。

至于“巨大”,你会想要更具体 - kb、mb、gb、tb?额外的问题将与 PHP 脚本在不被自动终止的情况下可以存活多长时间、脚本内存使用情况(这可能需要分块处理而不是加载整个文件)等有关。

编辑:啊,对于 RAW 帖子,我认为您将需要这个:Raw POST using Curl in PHP

于 2013-03-19T19:43:01.407 回答