If cURL is unavailable I want to send HTTP requests using fopen. I got the code for a class from a PACKT RESTful PHP book but it does nto work. Any ideas why?
if ($this->with_curl) {
//blah
} else {
$opts = array (
'http' => array (
'method' => "GET",
'header' => array($auth,
"User-Agent: " . RESTClient :: USER_AGENT . "\r\n"),
)
);
$context = stream_context_create($opts);
$fp = fopen($url, 'r', false, $context);
$result = fpassthru($fp);
fclose($fp);
}
return $result;
}
The HTTP context options are laid out here: http://www.php.net/manual/en/context.http.php
The
headeroption is a string, so as @Mob says you should be using\r\nand string concatenation rather than an array. However,user_agentis a valid key, so you could just use that instead.I’m guessing that the contents of the
$authvariable is something along the lines ofAuthorization: blah– i.e. standard header format?The below code is a working example. Note that I’ve changed your
fpassthru()(which outputs the content to the browser, and does not store it to$result) to afread()loop. Alternatively you could have wrapped thefpassthru()call withob_start();and$result = ob_get_clean();