PHP file get contents () y configuración de encabezados de solicitud


Con PHP, ¿es posible enviar encabezados HTTP con file_get_contents()?

Sé que puede enviar el agente de usuario desde su archivo php.ini. Sin embargo, también puede enviar otra información como HTTP_ACCEPT, HTTP_ACCEPT_LANGUAGE, y HTTP_CONNECTION con file_get_contents() ?

¿O hay otra función que logre esto?

 93
Author: Bogdan, 2010-01-21

7 answers

En realidad, al leer más sobre la función file_get_contents():

// Create a stream
$opts = [
    "http" => [
        "method" => "GET",
        "header" => "Accept-language: en\r\n" .
            "Cookie: foo=bar\r\n"
    ]
];

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);

Usted puede ser capaz de seguir este patrón para lograr lo que usted está buscando, aunque personalmente no he probado esto. (y si no funciona, no dude en revisar mi otra respuesta)

 253
Author: Dominic Barnes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-11 14:34:23

Esto es lo que funcionó para mí (a Dominic le faltaba solo una línea).

$url = "";

$options = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n" .  // check function.stream-context-create on php.net
              "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" // i.e. An iPad 
  )
);

$context = stream_context_create($options);
$file = file_get_contents($url, false, $context);
 77
Author: Fabrice,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-18 08:12:37

Puede usar esta variable para recuperar los encabezados de respuesta después de la función file_get_contents().

Código:

  file_get_contents("http://example.com");
  var_dump($http_response_header);

Salida:

array(9) {
  [0]=>
  string(15) "HTTP/1.1 200 OK"
  [1]=>
  string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT"
  [2]=>
  string(29) "Server: Apache/2.2.3 (CentOS)"
  [3]=>
  string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT"
  [4]=>
  string(27) "ETag: "280100-1b6-80bfd280""
  [5]=>
  string(20) "Accept-Ranges: bytes"
  [6]=>
  string(19) "Content-Length: 438"
  [7]=>
  string(17) "Connection: close"
  [8]=>
  string(38) "Content-Type: text/html; charset=UTF-8"
}
 37
Author: ali_sed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-24 11:18:36

Usar las bibliotecas php cURL probablemente será el camino correcto, ya que esta biblioteca tiene más características que la simple file_get_contents(...).

Un ejemplo:

<?php
$ch = curl_init();
$headers = array('HTTP_ACCEPT: Something', 'HTTP_ACCEPT_LANGUAGE: fr, en, da, nl', 'HTTP_CONNECTION: Something');

curl_setopt($ch, CURLOPT_URL, "http://localhost"); # URL to post to
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 ); # return into a variable
curl_setopt($ch, CURLOPT_HTTPHEADER, $header ); # custom headers, see above
$result = curl_exec( $ch ); # run!
curl_close($ch);
?>
 1
Author: phidah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-21 08:21:03

Sí.

Cuando se llama a file_get_contents en una url, se debe usar la función stream_create_context, que está bastante bien documentada en php.net

Esto se trata más o menos exactamente en la siguiente página en php.net en la sección de comentarios del usuario: http://php.net/manual/en/function.stream-context-create.php

 0
Author: Laereom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-24 09:00:46

Si no necesita HTTPS y curl no está disponible en su sistema, podría usar fsockopen

Esta función abre una conexión desde la que puede leer y escribir como lo haría con un controlador de archivo normal.

 0
Author: AlexB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-24 09:03:47

Desafortunadamente, no parece que file_get_contents() realmente ofrezca ese grado de control. La extensión cURL suele ser la primera en aparecer, pero recomiendo encarecidamente la extensión PECL_HTTP ( http://pecl.php.net/package/pecl_http ) para peticiones HTTP muy simples y directas. (es mucho más fácil de trabajar que cURL)

 -2
Author: Dominic Barnes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-21 08:19:20