Cómo publicar datos en PHP usando file get contents?


Estoy usando la función de PHP file_get_contents() para obtener el contenido de una URL y luego proceso encabezados a través de la variable $http_response_header.

Ahora el problema es que algunas de las URL necesitan algunos datos para ser publicados en la URL (por ejemplo, páginas de inicio de sesión).

¿Cómo hago eso?

Me doy cuenta de que usando stream_context puedo hacer eso, pero no estoy del todo claro.

Gracias.

Author: dnlcrl, 2010-03-15

3 answers

Enviar una solicitud HTTP POST usando file_get_contents no es tan difícil, en realidad : como adivinaste, tienes que usar el parámetro $context.


Hay un ejemplo dado en el manual de PHP, en esta página: HTTP context options (citando) :

$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

Básicamente, tienes que crear un stream, con las opciones correctas (hay una lista completa en esa página), y usarlo como tercer parámetro para file_get_contents nothing nada más; -)


Como nota al margen : en términos generales, para enviar solicitudes HTTP POST, tendemos a usar curl, que proporciona muchas opciones y todos streams pero los flujos son una de las cosas buenas de PHP que nadie conoce... lástima...

 521
Author: Pascal MARTIN,
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-03-15 05:44:26

Una alternativa, también puede usar fopen

$params = array('http' => array(
    'method' => 'POST',
    'content' => 'toto=1&tata=2'
));

$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if (!$fp)
{
    throw new Exception("Problem with $sUrl, $php_errormsg");
}

$response = @stream_get_contents($fp);
if ($response === false) 
{
    throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}
 17
Author: Macbric,
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
2013-06-09 19:29:08
$sUrl = 'http://www.linktopage.com/login/';
$params = array('http' => array(
    'method'  => 'POST',
    'content' => 'username=admin195&password=d123456789'
));

$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if(!$fp) {
    throw new Exception("Problem with $sUrl, $php_errormsg");
}

$response = @stream_get_contents($fp);
if($response === false) {
    throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}
 0
Author: user2525449,
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
2018-09-21 10:20:24