本篇文章主要介绍php中socket如何发送http请求,感兴趣的朋友参考下,希望对大家有所帮助。
socket方式:
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
//socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array("sec"=>20, "usec"=>0));
socket_connect($socket, 'www.baidu.com', 80);
//里面的换行代表 \r\n 注意拷贝的代码后面可能有空格
$http = <<
立即学习“PHP免费学习笔记(深入)”;
fsockopen方式:
$fp = fsockopen("www.baidu.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)
\n";
} else {
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: www.baidu.com\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $http);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
立即学习“PHP免费学习笔记(深入)”;
stream 方式(get):
$http = <<array(
'header' => $http,
'timeout'=>1, //超时 秒
'method' => 'GET', //默认方式
'protocol_version' => '1.1', //默认为 1.0
),
);
$context = stream_context_create($hdrs);
echo file_get_contents('http://www.baidu.com', 0, $context);
立即学习“PHP免费学习笔记(深入)”;
stream 方式 post:
$postdata = http_build_query(array('act'=>'save', 'id'=>387171));
$http = <<array(
'header' => $http,
'timeout'=>1, //超时 秒
'method' => 'POST',
'content' => $postdata,
'protocol_version' => '1.1', //默认为 1.0
),
);
$context = stream_context_create($hdrs);
echo file_get_contents('http://test.cm/song.php', 0, $context);
立即学习“PHP免费学习笔记(深入)”;
注意:http1.1 中必须包含 Host 头, 而 http1.0中则可以没有
总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。
相关推荐:
php基于CodeIgniter实现图片上传、剪切功能的方法
php metaphone()函数和php localeconv() 函数实例详解
立即学习“PHP免费学习笔记(深入)”;











