PHP如何发起HTTP请求

发布时间:2020-07-01 15:42:03 作者:元一
来源:亿速云 阅读:155

PHP如何发起HTTP请求?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

http请求是指从客户端到服务器端的请求消息。包括:消息首行中,对资源的请求方法、资源的标识符及使用的协议。从客户端到服务器端的请求消息包括,消息首行中,对资源的请求方法、资源的标识符及使用的协议。考虑到局限性更大的HTTP/0.9的向后兼容问题,有两种合法的HTTP请求格式。

PHP发起HTTP请求方式有:

1、file_get_contents发送get请求

<?php
/**
 * 发送post请求
 * @param string $url 请求地址
 * @param array $post_data post键值对数据
 * @return string
 */
function send_post($url, $post_data) {
    $postdata = http_build_query($post_data);
    $options = array(
        'http' => array(
            'method' => 'POST',
            'header' => 'Content-type:application/x-www-form-urlencoded',
            'content' => $postdata,
            'timeout' => 15 * 60 // 超时时间(单位:s)
        )
    );
    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    return $result;
}
$post_data = array(
'username' => 'abcdef',
'password' => '123456'
);
send_post('http://xxx.com', $post_data);

2、通过CURL发送get请求

<?php
$ch=curl_init('http://www.xxx.com/xx.html');
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_BINARYTRANSFER,true);
$output=curl_exec($ch);
$fh=fopen("out.html",'w');
fwrite($fh,$output);
fclose($fh);

3、通过fsocket发送get请求

/**
 * Socket版本
 * 使用方法:
 * $post_string = "app=socket&amp;version=beta";
 * request_by_socket('blog.snsgou.com', '/restServer.php', $post_string);
 */
function request_by_socket($remote_server,$remote_path,$post_string,$port = 80,$timeout = 30) {
$socket = fsockopen($remote_server, $port, $errno, $errstr, $timeout);
if (!$socket) die("$errstr($errno)");
fwrite($socket, "POST $remote_path HTTP/1.0");
fwrite($socket, "User-Agent: Socket Example");
fwrite($socket, "HOST: $remote_server");
fwrite($socket, "Content-type: application/x-www-form-urlencoded");
fwrite($socket, "Content-length: " . (strlen($post_string) + 8) . "");
fwrite($socket, "Accept:*/*");
fwrite($socket, "");
fwrite($socket, "mypost=$post_string");
fwrite($socket, "");
$header = "";
while ($str = trim(fgets($socket, 4096))) {
$header .= $str;
}
$data = "";
while (!feof($socket)) {
$data .= fgets($socket, 4096);
}
return $data;
}

关于PHP如何发起HTTP请求问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

推荐阅读:
  1. iphone发起http请求源码
  2. golang 发起http请求

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php http请求

上一篇:ossim系统原理与实践

下一篇:Log4j日志记录框架如何配置

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》