Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP requests with file_get_contents, getting the response code

I'm trying to use file_get_contents together with stream_context_create to make POST requests. My code so far:

    $options = array('http' => array(         'method'  => 'POST',         'content' => $data,         'header'  =>              "Content-Type: text/plain\r\n" .             "Content-Length: " . strlen($data) . "\r\n"     ));     $context  = stream_context_create($options);     $response = file_get_contents($url, false, $context); 

It works fine, however, when an HTTP error occurs, it spits out a warning:

file_get_contents(...): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request 

and returns false. Is there a way to:

  • suppress a warning (I'm planning to throw my own exception in case of failure)
  • obtain the error information (at least, the response code) from the stream
like image 239
georg Avatar asked Mar 25 '13 16:03

georg


1 Answers

http://php.net/manual/en/reserved.variables.httpresponseheader.php

file_get_contents("http://example.com", false, stream_context_create(['http' => ['ignore_errors' => true]])); var_dump($http_response_header); 
like image 108
Alles Avatar answered Nov 01 '22 08:11

Alles