Timeout for file_get_contents not working in PHP

I created a class for englobe of some HTTP methods in PHP. Here I have an HTTP POST method

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;
}

Basically, I create a $ header and use file_get_contents to POST some $ content in the URL. Everything seems to be working fine except for $ timeout. This is not considered. Even when I set it to 1, for example.

I do not see anything wrong, and I can not get the headers that I send.

Other similar questions here in SO suggest using Curl (I used it, but I am modifying get_contents_file for other reasons) or fsockopen, but that’s not what I need.

Is there some way to set a timeout using file_get_contents?

+4
2

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);
+1

, , options , :

<?php

set_time_limit(0);
ignore_user_abort(1);

$opts = array('http' =>
  array(
    'method'=>"POST",
    'timeout' => 60
  )
);

$context  = stream_context_create($opts);
$result = file_get_contents($url, false, $context);

:

Content-Length Content-type .


:

file_get_contents

+2

Source: https://habr.com/ru/post/1584359/


All Articles