在没有第三方库的情况下在PHP中生成HTTP请求
我想在PHP中发出在没有第三方库的情况下在PHP中生成HTTP请求,php,http,Php,Http,我想在PHP中发出DELETE,GET,POST,PUT请求,而不需要像cURL这样的第三方库 任何提示?一个选项是使用: 比自己使用fsockopen构建HTTP请求更简单的方法是使用标准函数: $fh = fopen('http://example.com', 'r'); while (!feof($fh)) { $content .= fread($fh, 8192); } fclose($fh); 然后,您可以使用发出更复杂的请求(例如,POST),该请求可以作为参数传递给f
DELETE
,GET
,POST
,PUT
请求,而不需要像cURL这样的第三方库
任何提示?一个选项是使用:
比自己使用
fsockopen构建HTTP请求更简单的方法是使用标准函数:
$fh = fopen('http://example.com', 'r');
while (!feof($fh)) {
$content .= fread($fh, 8192);
}
fclose($fh);
然后,您可以使用发出更复杂的请求(例如,POST
),该请求可以作为参数传递给fopen
:
$querystring = http_build_query(array(
'name' => 'SomeName',
'password' => 'SomePassword'
));
$context = stream_context_create(array(
'http' => array (
'method' => 'POST',
'content' => $querystring
)
));
$fh = fopen('http://example.com', 'r', false, $context);
// the request will be a POST
虽然fopen和fsockopen肯定可以工作,但另一个选项是使用。有了文件内容,您就不必担心如何读取数据。GET示例只是一个调用,如:
$data = file_get_contents($url);
要发出PUT请求,请将使用创建的上下文发送到第三个参数,如:
// Create stream
$headers = array(
"http" => array(
"method" => "PUT"
)
);
$context = stream_context_create($headers);
$data = file_get_contents($url, false, $context);
我认为这就是为什么php有cURL,必须有主机支持它。您可以使用file_GET_contents()函数获取,我想谢谢,我可以将POST请求的参数附加到查询字符串中吗?例如,@Marco请参见手册中的编辑和其他可添加的选项。
// Create stream
$headers = array(
"http" => array(
"method" => "PUT"
)
);
$context = stream_context_create($headers);
$data = file_get_contents($url, false, $context);