gpt4 book ai didi

php - 使用 fopen 和 curl_setopt 的 HTTP 请求

转载 作者:可可西里 更新时间:2023-11-01 16:24:47 24 4
gpt4 key购买 nike

如果 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;
}

最佳答案

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

header 选项是一个字符串,所以正如@Mob 所说,您应该使用 \r\n 和字符串连接而不是数组。但是,user_agent 是一个有效的 key ,因此您可以直接使用它。

我猜测 $auth 变量的内容与 Authorization: blah 类似 - 即标准 header 格式?

下面的代码是一个工作示例。请注意,我已将您的 fpassthru()(将内容输出到浏览器,并且不将其存储到 $result)更改为 fread() 循环。或者,您可以使用 ob_start();$result = ob_get_clean();

包装 fpassthru() 调用
<?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;

关于php - 使用 fopen 和 curl_setopt 的 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7928904/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com