file_get_contents的超时在PHP中不起作用
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了file_get_contents的超时在PHP中不起作用,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2217字,纯文字阅读大概需要4分钟。
内容图文
![file_get_contents的超时在PHP中不起作用](/upload/InfoBanner/zyjiaocheng/787/b3e20e88260b4856bf2e8b1a5f422b47.jpg)
我创建了一个类来在PHP中使用一些HTTP方法.在这里,我有一个HTTP POST的方法
public function post ($content, $timeout=null)
{
$timeInit = new DateTime();
$this->method = 'POST';
$header = array();
$header['header'] = null;
$header['content'] = is_array($content) ? http_build_query($content) : $content;
$header['method'] = $this->method;
if ($timeout != NULL) {
$header['header'] .= "timeout: $timeout"
}
$header['header'] .= "Content-length: ".strlen($header['content']);
$headerContext = stream_context_create(array('http' => $header));
$contents = file_get_contents($this->url, false, $headerContext);
$this->responseHeader = $http_response_header;
$timeFinal = new DateTime();
$this->time = $timeInit->diff($timeFinal);
return $contents;
}
基本上,我创建了一个$header并使用file_get_contents将一些$content发布到URL中.
显然,除了$timeout之外,一切正常.它不被考虑.例如,即使我将其设置为1.
我没有看到任何错误,我无法得到我正在发送的标题.
SO中的其他类似问题建议使用Curl(我正在使用它,但由于其他原因我正在更改file_get_contents)或fsockopen,但这不是我需要的.
存在一些使用file_get_contents设置超时的方法?
解决方法:
对于stream_context_create()http://php.net/manual/en/function.stream-context-create.php,它需要[array $options [,array $params]]
当你传递$header时,看起来你没有正确构建数组.会不会像这样的工作?
public function myPost($content, $timeout = null)
{
$timeInit = new DateTime();
$this->method = 'POST';
$header = array();
$header['header'] = null;
$header['content'] = is_array($content) ? http_build_query($content) : $content;
$header['method'] = $this->method;
if ($timeout) {
$header['header']['timeout'] = $timeout;
}
$header['header']['Content-length'] . strlen($header['content']);
$headerContext = stream_context_create(array('http' => $header));
$contents = file_get_contents($this->url, false, $headerContext);
$this->responseHeader = $http_response_header;
$timeFinal = new DateTime();
$this->time = $timeInit->diff($timeFinal);
return $contents;
}
但更好的方法是使用它,如例子所示,例如,
$timeInit = new DateTime();
// all your defaults go here
$opts = array(
'http'=>array(
'method'=>"POST",
)
);
//this way, inside conditions if you want
$opts['http']['header'] = "Accept-language: en\r\n" . "Cookie: foo=bar\r\n";
$context = stream_context_create($opts);
内容总结
以上是互联网集市为您收集整理的file_get_contents的超时在PHP中不起作用全部内容,希望文章能够帮你解决file_get_contents的超时在PHP中不起作用所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。