php使用socket调用http和smtp协议实例小结

本文实例讲述了php使用socket调用http和smtp协议。分享给大家供大家参考,具体如下:

socket发送HTTP请求

http协议请求报文格式

get

## 请求方法 请求文件路径?查询字符串 HTTP/协议版本号
## Host: 主机名:端口号
## Connection:close

post

## 请求方法 请求文件路径 HTTP/协议版本号
## Host: 主机名:端口号
## Content-type: application/x-www-form-urlencoded
## Content-length: 查询字符串长度
## Connection: close
## 查询字符串

api.php

<?php
echo $_SERVER["REQUEST_METHOD"]."<br/>";
print_r($_REQUEST);

fsocketopen发送get请求

<?php
$url = "api.php";
$host = "127.0.0.1";
$port = 8080;
$param = ["name"=>"zhezhao","age"=>23];
$url .= "?".http_build_query($param);
$socket = fsockopen($host,$port,$errno,$errstr,10);
$request = "GET /${url} HTTP/1.1\r\n";
$request .= "Host:${host}:{$port}\r\n";
$request .= "Connection:close\r\n\r\n";
fwrite($socket,$request);
echo "<b>Request:</b><br/>".str_replace("\r\n","<br/>",$request);
echo "<hr/><b>Response:</b><br/>";
$response = "";
while ($out = fread($socket, 2048)) {
 $response .= $out;
}
echo str_replace("\r\n","<br/>",$response);
fclose($socket);

sockets扩展发送post请求

<?php
$url = "api.php";
$host = "127.0.0.1";
$port = 8080;
$param = ["name"=>"zhezhao","age"=>23];
$data = http_build_query($param);
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, $host,$port);
$request = "POST /${url} HTTP/1.1\r\n";
$request .= "Host:${host}:{$port}\r\n";
$request .= "Content-type:application/x-www-form-urlencoded\r\n";
$request .= "Content-length:".strlen($data)."\r\n";
$request .= "Connection:close\r\n\r\n";
$request .= "${data}";
socket_write($socket,$request);
echo "<b>Request:</b><br/>".str_replace("\r\n","<br/>",$request);
echo "<hr/><b>Response:</b><br/>";
$response = "";
while ($out = socket_read($socket, 2048)) {
 $response .= $out;
}
echo str_replace("\r\n","<br/>",$response);
socket_close($socket);

socket发送smtp请求

首先通过socket连接到smtp服务器,例如smtp.163.com 25,然后实现smtp发送邮件的必须参数即可。

HELO 主机名
AUTH LOGIN base64编码之后的发件人邮箱
base64编码之后的密码
##填写信封

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/5682.html