简体   繁体   中英

HTTP request using fopen and curl_setopt

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 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 - ie 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;

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"
  )
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM