ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

file_get_contents的超时在PHP中不起作用

2019-06-28 16:15:14  阅读:191  来源: 互联网

标签:php file-get-contents connection-timeout


我创建了一个类来在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);

标签:php,file-get-contents,connection-timeout
来源: https://codeday.me/bug/20190628/1317551.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有