fsockopen除了像上面实例模拟生成 HTTP 连接之外,还能实现很多功能,比如模拟post 和 get 传送数据的方法。
get :
<?php
$url = "http://localhost/test2.php?site=www.tbrer.com";
print_r(parse_url($url));// 解析 URL,返回其组成部分
/* get提交 */
sock_get($url,'user=gonn');
// fsocket模拟get提交
function sock_get($url,$query){
$data = array(
'foo' => 'bar',
'baz' => 'boom',
'site' => 'www.tbrer.com',
'name' => 'nowa magic'
);
$query_str = http_build_query($data);// http_build_query()函数的作用是使用给出的关联(或下标)数组生成一个经过 URL-encode 的请求字符串
$info = parse_url($url);
$fp = fsockopen($info["host"],80,$errno,$errstr,30);
$head = "GET " . $info['path'] . '?' . $query_str . " HTTP/1.0\r\n";
$head .= "Host: " . $info['host'] . "\r\n";
$head .= "\r\n";
$write = fputs($fp,$head);
while(!feof($fp)){
$line = fread($fp,4096);
echo $line;
}
}
?>
<?php
$url = "http://localhost/test2.php?site=www.tbrer.com";
print_r(parse_url($url));// 解析 URL,返回其组成部分
/* post提交 */
sock_post($url,'user=gonn');
// fsocket模拟post提交
function sock_post($url,$query){
$info = parse_url($url);
$fp = fsockopen($info["host"],80,$errno,$errstr,30);
$head = "POST " . $info['path'] . "?" . $info["query"] . " HTTP/1.0\r\n";
$head .= "Host: " . $info['host'] . "\r\n";
$head .= "Referer: http://" . $info['host'] . $info['path'] . "\r\n";
$head .= "Content-type: application/x-www-form-urlencoded\r\n";
$head .= "Content-Length: ". strlen(trim($query)) . "\r\n";
$head .= "\r\n";
$head .= trim($query);
$write = fputs($fp,$head);
while(!feof($fp)){
$line = fread($fp,4096);
echo $line;
}
}
?>
接收页面 test2.php 的代码为:
<?php
$data = $_REQUEST;
echo '<pre>';
print_r($data);
echo '</pre>';
?>
————————————————
原文链接:https://blog.csdn.net/zjsfdx/article/details/89376176