将 PUT 方法与 PHP cUrl 库结合使用

2022-08-30 16:16:48

我能够成功运行以下 curl 命令(在命令行中):

curl -XPOST --basic -u user:password -H accept:application/json -H Content-type:application/json --data-binary '{ "@queryid" : 1234 }' http://localhost/rest/run?10

以下是我到目前为止正在做的事情,但它似乎没有与我正在使用的REST服务一起使用:

$headers = array(
    'Accept: application/json',
    'Content-Type: application/json',
);

$url = 'http://localhost/rest/run?10';
$query = '{ "@queryid" : 1234 }';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "user:password");

curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
curl_setopt($ch, CURLOPT_POSTFIELDSIZE, strlen($query));

$output = curl_exec($ch);

echo $output;

尝试使用 PUT 方法转换 --data-binary 时,正确的方法是什么?


答案 1

您可以使用 .,而不是在磁盘上创建临时文件。php://temp

$body = 'the RAW data string I want to send';

/** use a max of 256KB of RAM before going to disk */
$fp = fopen('php://temp/maxmemory:256000', 'w');

if (!$fp) 
{
    die('could not open temp memory data');
}

fwrite($fp, $body);
fseek($fp, 0); 

curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_INFILE, $fp); // file pointer
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($body));                            

好处是没有磁盘IO,因此它应该更快,并且服务器上的负载更少。


答案 2

嗨,我都使用它来工作:

// Start curl
$ch = curl_init();
// URL for curl
$url = "http://localhost/";

// Clean up string
$putString = stripslashes($query);
// Put string into a temporary file
$putData = tmpfile();
// Write the string to the temporary file
fwrite($putData, $putString);
// Move back to the beginning of the file
fseek($putData, 0);

// Headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Binary transfer i.e. --data-BINARY
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
// Using a PUT method i.e. -XPUT
curl_setopt($ch, CURLOPT_PUT, true);
// Instead of POST fields use these settings
curl_setopt($ch, CURLOPT_INFILE, $putData);
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($putString));

$output = curl_exec($ch);
echo $output;

// Close the file
fclose($putData);
// Stop curl
curl_close($ch);

:)


推荐