You need to send a GET / POST request and receive a response code, the received content does not matter. Is it possible to implement this? Preferably without curl.

2 answers 2

We get only the headers and check the response code:

 $url = 'http://stackoverflow.com'; $headers = @get_headers($url); if (!empty($headers[0])) { preg_match('/\d{3}/', $headers[0], $matches); echo $matches[0] . PHP_EOL; } 

Although there is no particular difference in obtaining a complete answer, a regular HTTP / 1.0 request will come to the server.

Results get_headers:

 $headers = get_headers($url, 0); array(14) { [0]=> string(15) "HTTP/1.1 200 OK" [1]=> string(35) "Date: Fri, 25 Mar 2016 08:39:49 GMT" [2]=> string(38) "Content-Type: text/html; charset=utf-8" ... $headers = get_headers($url, 1); array(13) { [0]=> string(15) "HTTP/1.1 200 OK" ["Date"]=> string(29) "Fri, 25 Mar 2016 08:40:48 GMT" ["Content-Type"]=> string(24) "text/html; charset=utf-8" ... 

To send POST requests, curl can be used and received from the http-status response. Moreover, with POST, data is usually sent.

As noted by @BOPOH, via get_headres and add. headers can be transferred, including setting the HEAD or POST method. Example with POST method:

 stream_context_set_default( array( 'http' => array( 'method' => 'POST', 'header' => "Accept-language: en\r\n", ) ) ); $url = 'http://stackoverflow.com'; $headers = get_headers($url); 

stackoveflow cursed that string (28) "HTTP / 1.1 411 Length Required" should have POST data, on some resources with empty POST data, and 200 answers.

  • I'm not sure that get_headers() normally performs with a post request. You would check and if it works, you would write it in response with a sample code - BOPOH
  • @BOPOH POST requests fail, get_headers only for GET requests .. - jekaby
  • so there you can also transmit the context - it also does not help? I just have to check laziness myself))) of my affairs - BOPOH
  • Looked, get_headers has the second optional parameter $ format. If it has a nonzero value, then the headers are broken down by keys. Those. if it was in array 1 => "Server: nginx / 1.6.2", then it becomes 'Server' => 'nginx / 1.6.2'. And the method is still GET) - jekaby
  • one
    You can see there Example # 2 An example of using the HEAD request in the get_headers () function - it says that get is used by default, but you can also use head. But you can ask via stream_context_set_default and post, only if it works - I don’t know, maybe it will ignore it and get it (I’m talking about it) - BOPOH

Via file_get_contents

 function getStatusCode($url, $method) { file_get_contents($url, null, stream_context_create(['http' => ['method' => $method]])); return $http_response_header[0]; } // "HTTP/1.1 200 OK" var_dump( getStatusCode('https://habrahabr.ru', 'GET') ); // "HTTP/1.1 200 OK" var_dump( getStatusCode('https://habrahabr.ru', 'POST') ); // "HTTP/1.1 403 Forbidden" var_dump( getStatusCode('https://ya.ru', 'POST') );