使用fopen和curl_setopt的HTTP请求

Lee*_*Tee 2 php fopen curl http

如果cURL不可用,我想使用fopen发送HTTP请求.我从PACKT RESTful PHP书中获得了一个类的代码,但它没有工作.有什么想法吗?

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;
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*jie 7

HTTP上下文选项在此处列出:http://www.php.net/manual/en/context.http.php

header选项是一个字符串,因此@Mob说你应该使用\r\n和字符串连接而不是数组.但是,它user_agent是一个有效的密钥,因此您可以使用它.

我猜测$auth变量的内容是Authorization: blah符合标准的标题格式?

下面的代码是一个工作示例.请注意,我已将您fpassthru()的内容(将内容输出到浏览器,而不是将其存储到$result)fread()循环.或者你可以fpassthru()ob_start();和包裹来电$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;
Run Code Online (Sandbox Code Playgroud)