您的位置:首页 > 理论基础 > 计算机网络

php模拟http请求 4000

2015-11-22 17:43 609 查看

Php模拟http请求

今天有空,于是总结一下php模拟http请求的方式。如果有错漏,希望大家可以提出来,大家一起分享一起学习。
 

方法一:File_get_contents(只能模拟get请求)

$url = “http://www.baidu.com”;

$content = File_get_contents($url);

 

方法二:Fsockopen

模拟请求行、请求头、空行、请求内容(post请求)

Get:

可以用parse_url($url)函数获取url信息

 打开链接

$f = fsockopen(‘域名/ip’,端口,$errno,$error,连接时长);

模拟请求

$http = “GET /index.htmlHTTP/1.1 \r\n”;

$http .= “Host:localhost\r\n”;

$http .= “\r\n”;

写入资源

Fwirte($f,$http);                         //or fputs

获取数据(可能需要遍历)

Fgetc()/fgets()/fread()

处理数据

输出 or 写下(txt/db)

 

Post:(数据长度和转码协议必须要有)

….

//模拟请求

$http = “POST /index.html HTTP/1.1 \r\n”;

$http .= “Host:localhost\r\n”;

$http .= “Connection:keep-alive\r\n”;

$http .= “Content-length:43\r\n”;  //长度最好与数据长度一致(要求知道接口返回的数据长度)

$http .= “Content-type:application/x-www-form”;

$http .= “\r\n”

$http .= “u_name=george&password=123”;

...

 

 

方法三:curl

 

$url

$ch = Curl_init($url);

配置(具体可以网上搜索一下curl的配置)

Curl_setopt($ch,XXXXXX)

Curl_setopt($ch,XXXXXX)



Curl_setopt($ch,XXXXXX)

$data = curl_exec($ch)

//处理数据

输出 or 写下(txt/db)

//关闭资源

curl_close($ch)

 

curl_error($ch)         //输出错误信息
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php