在没有第三方库的情况下在PHP中发出HTTP请求

时间:2010-12-27 15:31:28

标签: php http

我想在PHP中发出DELETEGETPOSTPUT请求,而不需要像cURL这样的第三方库。

任何提示?

3 个答案:

答案 0 :(得分:4)

一种选择是使用fsockopen()

<?php
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    $out = "GET / HTTP/1.1\r\n";
    $out .= "Host: www.example.com\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}
?>

答案 1 :(得分:4)

使用fsockopen自行构建HTTP请求比使用标准fopen函数更简单:

$fh = fopen('http://example.com', 'r');
while  (!feof($fh)) {
    $content .= fread($fh, 8192);
}
fclose($fh);

然后,您可以使用stream_context_create制作更复杂的请求(例如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

答案 2 :(得分:2)

虽然fopen和fsockopen肯定有效,但另一个选择是使用file_get_contents。使用file_get_contents,您不必担心如何读取数据。 GET示例只是一个调用,如:

$data = file_get_contents($url);

要发出PUT请求,请将使用stream_context_create创建的上下文发送到第三个参数,例如:

// Create stream
$headers = array(
  "http" => array(
    "method" => "PUT"
  )
);

$context = stream_context_create($headers);
$data = file_get_contents($url, false, $context);