POST headers in file_get_contents

// Create a stream
$opts = array(
  'http'=>array(
    'method'=>"POST",
    'header'=>"Accept-language: en\\r\
" .
              "Cookie: foo=bar\\r\
"
  )
);

$context = stream_context_create($opts);

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

The above code shows how to put headers in a file_get_contents, but I’m not sure how to include the POST field values. Anyone know how it works?

There’s a good example in the manual:


<?php
$data = array ('foo' => 'bar', 'bar' => 'baz');
$data = http_build_query($data);

$context_options = array (
        'http' => array (
            'method' => 'POST',
            'header'=> "Content-type: application/x-www-form-urlencoded\\r\
"
                . "Content-Length: " . strlen($data) . "\\r\
",
            'content' => $data
            )
        );

$context = context_create_stream($context_options)
$fp = fopen('https://url', 'r', false, $context);
?>

Where $data is the POST data to send to the server.

Any particular reason you’re not using cURL btw? It’s lot easier and more readable than working with streams IMO.

I’m not sure how to use curl well and file_get_contents is so easy. Thanks for the info Scallio!