我的以下代码存在一些问题:
<?php
$url = "192.168.0.1:10040";
$xml = '<root><list><MatrixConnectionList><DviConsole type="name">Monitor X</DviConsole></MatrixConnectionList></list></root>';
$headers = array(
"Content-type: text/xml",
"Content-length: " . strlen($xml),
"Connection: close",
);
//Execute the curl init
$ch = curl_init();
//Add URL to Curl
curl_setopt($ch, CURLOPT_URL, $url);
//Return response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//set timeout
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
//Add post option to curl
curl_setopt($ch, CURLOPT_POST, true);
//Add curel post field
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
//Add headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//Add verbose for error logging
curl_setopt($ch, CURLOPT_VERBOSE, true);
//Execute Curl
$data = curl_exec($ch);
//Print response
error_log(print_r($xml, TRUE));
error_log(print_r($data, TRUE));
//Log errors and close curl
if(curl_errno($ch))
print curl_error($ch);
else
curl_close($ch);
?>
响应应类似于:
<?xml version="1.0" encoding="utf-8"?><root><result type="list"><MatrixConnectionList><item><cpuId>0x0000</cpuId><cpuCl>DviCpu</cpuCl><cpuName>MISC</cpuName><cpuPoweredOn>true</cpuPoweredOn><signalType>viewonly</signalType><consoleId>0x000000</consoleId><consoleCl>DviConsole</consoleCl><consoleName>Monitor X</consoleName><connectionOwnerId>0x00000000</connectionOwnerId><connectionOwnerCl>DviMatrix</connectionOwnerCl><connectionOwnerPort>2</connectionOwnerPort><connectionOwnerName>Matrix X</connectionOwnerName><consoleConfigEnable>1</consoleConfigEnable><consolePoweredOn>true</consolePoweredOn><userName>0000000</userName><transmission>2</transmission></item></MatrixConnectionList></result></root>
除了检查Apache错误日志外,我看到以下内容:
* upload completely sent off: 118 out of 118 bytes
* Operation timed out after 5001 milliseconds with 1456 out of -1 bytes received
[Thu Apr 30 10:48:05.967278 2020] [php7:notice] [pid 20251] [client 192.168.0.2:6000] , referer: http://192.168.0.1/pages/test.php
我在这里想念什么吗?为什么curl_exec不将返回的字符串分配给我的变量。
谢谢!
答案 0 :(得分:0)
您遇到的服务器没有发送Content-Length
标头(要么根本不发送,要么发送格式不正确的标头,我不确定,您可以检查详细的日志以了解信息) ,这会使curl一直保持读取状态,直到远程服务器关闭套接字为止,并且服务器用了5秒钟以上的时间关闭了套接字,而5秒钟似乎是您的默认CURLOPT_TIMEOUT,所以出现了超时错误。 CURLOPT_RETURNTRANSFER错误,curl_exec()不会返回响应字符串,而是返回bool(false)表示发生了错误。
您可以尝试增加CURLOPT_TIMEOUT来查看服务器是否最终将关闭套接字,
// timeout at 10 seconds instead of 5, server reponds slowly sometimes..
curl_setopt($ch,CURLOPT_TIMEOUT,10);
或者您可以删除
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
并添加
$response="";
curl_setopt($ch,CURLOPT_WRITEFUNCTION,function($ch,string $data)use(&$response):int{
$response.=$data;
return strlen($data);
});
$error_if_false=curl_exec($ch);
if(false===$error_if_false){
// error, but your response is now in $response regardless.
}