Reputation: 6601
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;
}
Upvotes: 2
Views: 6715
Reputation: 7946
The HTTP context options are laid out here: http://www.php.net/manual/en/context.http.php
The header
option is a string, so as @Mob says you should be using \r\n
and string concatenation rather than an array. However, user_agent
is a valid key, so you could just use that instead.
I'm guessing that the contents of the $auth
variable is something along the lines of Authorization: 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 a fread()
loop. Alternatively you could have wrapped the fpassthru()
call with ob_start();
and $result = ob_get_clean();
<?php
class RESTClient {
const USER_AGENT = 'bob';
}
$url = 'http://www.example.com/';
$username = "fish";
$password = "paste";
$b64 = base64_encode("$username:$password");
$auth = "Authorization: Basic $b64";
$opts = array (
'http' => array (
'method' => "GET",
'header' => $auth,
'user_agent' => RESTClient :: USER_AGENT,
)
);
$context = stream_context_create($opts);
$fp = fopen($url, 'r', false, $context);
$result = "";
while ($str = fread($fp,1024)) {
$result .= $str;
}
fclose($fp);
echo $result;
Upvotes: 8
Reputation: 11098
You're mixing this. Shouldn't it be ::
$opts = array (
'http' => array (
'method' => "GET",
'header' => $auth . "\r\n" . //removed array()
"User-Agent: " . RESTClient :: USER_AGENT . "\r\n" )
)
Here's an example of setting headers from the PHP manual
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
Upvotes: 1