PHP更原始的发送http请求方式

23-09-27 17:00 字数 1675 阅读 2317 已编辑

项目中通常使用file_get_contents和curl,除此之外,通过fopen,fsockopen,stream_socket_client等也可实现,示例过于简单,仅供了解

$url = 'https://www.baidu.com/';
$urlArr = parse_url($url);
$path = $urlArr['path'] ?? '/';

$data = "GET $path HTTP/1.1" . PHP_EOL;
$data .= "Host: {$urlArr['host']}" . PHP_EOL;
$data .= "Connection: Close" . PHP_EOL . PHP_EOL;


// fopen
$resource = fopen($url, 'r');
if (!$resource) {
    echo 'Connect failed' . PHP_EOL;
    exit;
}
fwrite($resource, $data);
$content = '';
while (!feof($resource)) {
    $content .= fgets($resource);
}
echo $content . PHP_EOL;
fclose($resource);


// fsockopen
$resource = fsockopen('ssl://' . $urlArr['host'], 443, $errorCode, $errorMsg);
//$resource = fsockopen('tcp://' . $urlArr['host'], 80, $errorCode, $errorMsg);
if (!$resource) {
    echo sprintf('Connect failed, errorCode: %d, errorMsg: %s', $errorCode, $errorMsg) . PHP_EOL;
    exit;
}
fwrite($resource, $data);
$content = '';
while (!feof($resource)) {
    $content .= fgets($resource);
}
echo $content . PHP_EOL;
fclose($resource);


// stream_socket_client
$resource = stream_socket_client('ssl://' . $urlArr['host'] . ':443', $errorCode, $errorMsg);
//$resource = stream_socket_client('tcp://' . $urlArr['host'] . ':80', $errorCode, $errorMsg);
if (!$resource) {
    echo sprintf('Connect failed, errorCode: %d, errorMsg: %s', $errorCode, $errorMsg) . PHP_EOL;
    exit;
}
fwrite($resource, $data);
$content = '';
while (!feof($resource)) {
    $content .= fgets($resource);
}
echo $content . PHP_EOL;
fclose($resource);


// 响应header和body
$separator = '/\r\n\r\n|\n\n|\r\r/';
list($header, $body) = preg_split($separator, $content);
echo $header . PHP_EOL;
echo $body . PHP_EOL;
0人点赞>
关注 收藏 改进 举报
0 条评论
排序方式 时间 投票
快来抢占一楼吧
请登录后发表评论