1.cURL
<?phpclass IndexController extends ControllerBase{ ???public function indexAction() ???{ ???????$postfields = array(‘name‘=>‘刘的话liudehua‘,‘age‘=>‘199‘); ???????$this->mycurl(‘http://127.0.0.1:8888‘,http_build_query($postfields)); ???????$this->log->debug("fssss"); ???????//phpinfo(); ???????die; ???} ???public function getHeader(){ ???????echo "getheader<br>"; ???} ???public function mycurl($url, ?$postfields = NULL, $method=‘POST‘){ ???????//$url = "http://127.0.0.1:8888"; ???????$timeout = 10;//超时时间 ???????$connectTimeout = 0;//无限等待 ???????$ssl = substr($url, 0, 8) == "https://" ? true : false; ???????????????//开始curl ???????$ci = curl_init(); ???????//设置curl使用的HTTP协议,CURL_HTTP_VERSION_NONE(让curl自己判断),CURL_HTTP_VERSION_1_0(HTTP/1.0),CURL_HTTP_VERSION_1_1(HTTP/1.1) ???????curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); ???????//curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent); ???????//在HTTP请求中包含一个”user-agent”头的字符串。 ???????curl_setopt($ci, CURLOPT_USERAGENT,‘Opera/9.80 (Windows NT 6.2; Win64; x64) Presto/2.12.388 Version/12.15‘); ???????curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $connectTimeout); //在发起连接前等待的时间,如果设置为0,则无限等待 ???????curl_setopt($ci, CURLOPT_TIMEOUT, $timeout); ???????//如果成功只返回TRUE,自动输出返回的内容。如果失败返回FALSE ???????curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE); ???????//header中“Accept-Encoding: ”部分的内容,支持的编码格式为:"identity","deflate","gzip"。如果设置为空字符串,则表示支持所有的编码格式 ???????curl_setopt($ci, CURLOPT_ENCODING, ""); ???????if ($ssl) { ???????????curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书 浏览器访问https的时候,浏览器会自动加载网站的安全证书进行加密 ???????????curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, 1); // 检查证书中是否设置域名 ???????} ???????//避免data数据过长问题 设置一个header中传输内容的数组 ???????//curl_setopt($ci, CURLOPT_HTTPHEADER, array(‘Expect:‘)); ???????//curl_setopt($ch, CURLOPT_HTTPHEADER, array(‘Content-Type: application/json‘,‘Content-Length:‘.strlen($curlPost))); ???????//设置一个回调函数,这个函数有两个参数,第一个是curl的资源句柄,第二个是输出的header数据。header数据的输出必须依赖这个函数,返回已写入的数据大小 ???????curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, ‘getHeader‘)); ???????//如果你想把一个头包含在输出中,设置这个选项为一个非零值。 ???????curl_setopt($ci, CURLOPT_HEADER, FALSE); ???????????????switch ($method) { ???????????case ‘POST‘: ???????????????curl_setopt($ci, CURLOPT_POST, TRUE); ???????????????if (!empty($postfields)) { ???????????????????curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields); ???????????????} ???????????????break; ???????????case ‘DELETE‘: ???????????????curl_setopt($ci, CURLOPT_CUSTOMREQUEST, ‘DELETE‘); ???????????????if (!empty($postfields)) { ???????????????????$url = "{$url}?{$postfields}"; ???????????????} ???????} ???????curl_setopt($ci, CURLOPT_URL, $url); ???????//发送请求的字符串头 ???????curl_setopt($ci, CURLINFO_HEADER_OUT, TRUE); ???????????????$response ?= curl_exec($ci); ???????$http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE); ???????if($response === false) ???????{ ???????????$error = curl_error($ci); ???????????echo "发送失败"; ???????????var_export($error); ???????}else{ ???????????echo "成功发送:".var_export($response); ???????} ???????curl_close ($ci); ???????????} ???public function setmemAction(){ ???????$mem=new Memcached(); //实例化Memcached类 ?/* ??????$server= array( ???????????array(‘localhost‘,11200), ???????); */ ???????$isok = $mem->addServer(‘localhost‘,11200); ???????var_dump($mem->getStats());die; ???????$issetm = $mem->set(‘name‘,‘网络管理nginx‘,0); ////设置缓存值,有效时间3600秒,如果有效时间设置为0,则表示该缓存值永久存在的(系统重启前) ???????echo $mem->get(‘name‘); ???} ???public function getmemAction(){ ???????$mem=new Memcached(); //实例化Memcached类 ???????$server= array( ???????????array(‘localhost‘,11200), ???????); ???????$isok = $mem->addServers($server); ???????var_dump($isok); ???????echo $mem->get(‘name‘); ???} ???public function testdbAction(){ ???????$dbhost = ‘localhost:3306‘; ?// mysql服务器主机地址 ???????$dbuser = ‘daokrdb‘; ???????????// mysql用户名 ???????$dbpass = ‘123456‘; ?????????// mysql用户名密码 ???????$conn = mysqli_connect($dbhost, $dbuser, $dbpass); ???????if(! $conn ) ???????{ ???????????die(‘Could not connect: ‘ . mysqli_error()); ???????} ???????echo ‘数据库连接成功!‘; ???????// 设置编码,防止中文乱码 ???????mysqli_query($conn , "set names utf8"); ???????????????//使用哪个个数据库 ???????mysqli_select_db( $conn, ‘daokrdb‘ ); ???????$sql = ‘SELECT * FROM t_users‘; ???????$retval = mysqli_query( $conn, $sql ); ???????if(! $retval ) ???????{ ???????????die(‘无法读取数据: ‘ . mysqli_error($conn)); ???????} ???????echo ‘<table border="1" width="100%"><tr><td>教程 ID</td><td>标题</td><td>作者</td><td>提交日期</td></tr>‘; ???????while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) ???????{ ???????????echo "<tr><td> {$row[‘id‘]}</td> ". ???????????????"<td>{$row[‘title‘]} </td> ". ???????????????"<td>{$row[‘author‘]} </td> ". ???????????????"<td>{$row[‘submission_date‘]} </td> ". ???????????????"</tr>"; ???????} ???????echo ‘</table>‘; ???????mysqli_close($conn); ???} ???????public function redisAction(){ ???????$redis = new Redis(); ???????$redis->connect(‘127.0.0.1‘, 6379); ???????echo "Connection to server sucessfully<br/>"; ???????//存储数据到列表中 ???????$redis->lpush("tutorial-list", "Redis"); ???????$redis->lpush("tutorial-list", "Mongodb"); ???????$redis->lpush("tutorial-list", "Mysql"); ???????// 获取存储的数据并输出 ???????$arList = $redis->lrange("tutorial-list", 0 ,5); ???????echo "Stored string in redis------<br/>"; ???????echo"压入队列:<br/>";var_export($arList); ???????echo "<br/>"; ???????// 获取列表长度 ???????$llen = $redis->llen(‘tutorial-list‘); ???????while ($llen){ ???????????echo "弹出数据:".$redis->lpop(‘tutorial-list‘)."<br/>"; ???????????$llen = $redis->llen(‘tutorial-list‘); ???????} ???????// 获取存储的数据并输出 ???????$arList = $redis->lrange("tutorial-list", 0 ,5); ???????echo "Stored string in redis------<br/>"; ???????var_export($arList); ???} ???//测试reds ???public function testredisAction(){ ?????????????$store=10; ???????$redis=new Redis(); ???????$result=$redis->connect(‘127.0.0.1‘,6379); ???????$res=$redis->llen(‘goods_store‘); ???????echo $res."<br>"; ???????$count=$store-$res; ???????for($i=0;$i<$count;$i++){ ???????????$redis->lpush(‘goods_store‘,1); ???????} ???????echo $redis->llen(‘goods_store‘); ???????????} ???public function buyAction(){ ???????//模拟下单操作 ???????//下单前判断redis队列库存量 ???????$redis=new Redis(); ???????$result=$redis->connect(‘127.0.0.1‘,6379); ???????$count=$redis->lpop(‘goods_store‘); ???????echo $count."<br>"; ???????echo $redis->llen(‘goods_store‘)."<br>"; ???????if(!$count){ ???????????echo(‘error:no store redis‘); ???????}else{ ???????????//生成订单 ???????????$order_sn=$this->build_order_no(); ???????????echo $order_sn; ???????} ???????????} ???//生成唯一订单号 ???function build_order_no(){ ???????return date(‘ymd‘).substr(implode(NULL, array_map(‘ord‘, str_split(substr(uniqid(), 7, 13), 1))), 0, 8); ???} ???//正则表达式 ???public function pregAction(){ ???????//使用逗号或空格(包含" ", \r, \t, \n, \f)分隔短语 ???????$str = "hypertext language, programming‘name wokd"; ???????$keywords = preg_split("/[\s\‘]+/", $str); ???????print_r($keywords); ???????//替换 ???????$string = ‘language 15, 2003‘; ???????$pattern = ‘/(\w+) (\d+), (\d+)/i‘; ???????$replacement = ‘wangxiaomai 09,$3‘; ???????echo "<br>"; ???????echo preg_replace($pattern, $replacement, $string); ???????????????echo "<br>"; ???????$array = array("23.32","22","12.009","26666.43.43","88899.777.888.444","g9","Uafdsfasdfadsfsd10","#9");// ? 匹配前面的子表达式零次或一次 ???????print_r(preg_grep("/^(\d+)\.(\d+)\.(\d+)$/",$array)); ???????echo "<br>"; ???????print_r(preg_grep("/^[a-zA-Z]{1,}[0-9]{1,}$/",$array)); ???????????????//从URL中获取主机名称 ???????preg_match(‘@^(?:http://)?([^/]+)@i‘,"http://www.php.net/index.html", $matches); ???????$host = $matches[1]; ???????????????????????//获取主机名称的后面两部分 ???????preg_match(‘/[^.]+\.[^.]+$/‘, $host, $matches); ???????echo "domain name is: {$matches[0]}\n"; ???????????????echo "<br>"; ???????echo gethostname(); ???????????}}
2.stream流的方式
stream_context_create — 创建资源流上下文
stream_context_create 作用:创建并返回一个文本数据流并应用各种选项,
可用于 fopen(), file_get_contents() 等过程的超时设置、代理服务器、请求方式、头信息设置的特殊过程。
例子:
<?phpfunction post($url, $data){ ?$postdata = http_build_query( ???$data ?); ??$opts = array(‘http‘ => ??????????array( ????????????‘method‘ => ‘POST‘, ????????????‘header‘ => ‘Content-type: application/x-www-form-urlencoded‘, ????????????‘content‘ => $postdata ??????????) ?); ?$context = stream_context_create($opts); ?$result = file_get_contents($url, false, $context); ?return $result;}
3.socket方式
使用套接字建立连接,拼接 HTTP 报文发送数据进行 HTTP 请求。
fsockopen — 打开一个网络连接或者一个Unix套接字连接
说明
$hostname
[, int $port
= -1 [, int &$errno
[, string &$errstr
[, float $timeout
= ini_get("default_socket_timeout") ]]]] )初始化一个套接字连接到指定主机(hostname
)。
PHP支持以下的套接字传输器类型列表 所支持的套接字传输器(Socket Transports)列表。也可以通过stream_get_transports()来获取套接字传输器支持类型。
默认情况下将以阻塞模式开启套接字连接。当然你可以通过stream_set_blocking()将它转换到非阻塞模式。
stream_socket_client()与之非常相似,而且提供了更加丰富的参数设置,包括非阻塞模式和提供上下文的的设置。
参数
hostname
如果安装了OpenSSL,那么你也许应该在你的主机名地址前面添加访问协议ssl://或者是tls://,从而可以使用基于TCP/IP协议的SSL或者TLS的客户端连接到远程主机。
port
端口号。如果对该参数传一个-1,则表示不使用端口,例如unix://。
errno
如果传入了该参数,holds the system level error number that occurred in the system-level connect() call。
如果
errno
的返回值为0,而且这个函数的返回值为FALSE
,那么这表明该错误发生在套接字连接(connect())调用之前,导致连接失败的原因最大的可能是初始化套接字的时候发生了错误。errstr
错误信息将以字符串的信息返回。
timeout
设置连接的时限,单位为秒。
Note:
注意:如果你要对建立在套接字基础上的读写操作设置操作时间设置连接时限,请使用stream_set_timeout(),fsockopen()的连接时限(
timeout
)的参数仅仅在套接字连接的时候生效。
返回值
fsockopen()将返回一个文件句柄,之后可以被其他文件类函数调用(例如:fgets(),fgetss(),fwrite(),fclose()还有feof())。如果调用失败,将返回FALSE
。
<?php$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);if (!$fp) { ?echo "$errstr ($errno)<br />\n";} else { ?$out = "GET / HTTP/1.1\r\n"; ?$out .= "Host: www.example.com\r\n"; ?$out .= "Connection: Close\r\n\r\n"; ?fwrite($fp, $out); ?while (!feof($fp)) { ???echo fgets($fp, 128); ?} ?fclose($fp);}?>
用fsockopen 以post方式获取数据
1 <?php ??2 function HTTP_Post($URL,$data,$cookie, $referrer="") ??3 { ??4 ????// parsing the given URL ??5 $URL_Info=parse_url($URL); ??6 ????// Building referrer ??7 if($referrer=="") // if not given use this script as referrer ??8 $referrer="111"; ??9 ????// making string from $data ?10 foreach($data as $key=>$value) ?11 $values[]="$key=".urlencode($value); ?12 $data_string=implode("&",$values); ?13 ????// Find out which port is needed - if not given use standard (=80) ?14 if(!isset($URL_Info["port"])) ?15 $URL_Info["port"]=80; ?16 ????// building POST-request: ?17 $request.="POST ".$URL_Info["path"]." HTTP/1.1\n"; ?18 $request.="Host: ".$URL_Info["host"]."\n"; ?19 $request.="Referer: $referer\n"; ?20 $request.="Content-type: application/x-www-form-urlencoded\n"; ?21 $request.="Content-length: ".strlen($data_string)."\n"; ?22 $request.="Connection: close\n"; ?23 ????$request.="Cookie: ??$cookie\n"; ?24 ????$request.="\n"; ?25 $request.=$data_string."\n"; ?26 ????$fp = fsockopen($URL_Info["host"],$URL_Info["port"]); ?27 fputs($fp, $request); ?28 while(!feof($fp)) { ?29 $result .= fgets($fp, 1024); ?30 } ?31 fclose($fp); ?32 ????return $result; ?33 } ?34 ?>
用fsockopen函数打开url,以get方式获取完整的数据,包括header和body,fsockopen需要 PHP.ini 中
allow_url_fopen 选项开启
1 <?php ??2 function get_url ($url,$cookie=false) ??3 { ??4 $url = parse_url($url); ??5 $query = $url[path]."?".$url[query]; ??6 echo "Query:".$query; ??7 $fp = fsockopen( $url[host], $url[port]?$url[port]:80 , $errno, $errstr, 30); ??8 if (!$fp) { ??9 return false; ?10 } else { ?11 $request = "GET $query HTTP/1.1\r\n"; ?12 $request .= "Host: $url[host]\r\n"; ?13 $request .= "Connection: Close\r\n"; ?14 if($cookie) $request.="Cookie: ??$cookie\n"; ?15 $request.="\r\n"; ?16 fwrite($fp,$request); ?17 while()) { ?18 $result .= @fgets($fp, 1024); ?19 } ?20 fclose($fp); ?21 return $result; ?22 } ?23 } ?24 //获取url的html部分,去掉header ?25 function GetUrlHTML($url,$cookie=false) ?26 { ?27 $rowdata = get_url($url,$cookie); ?28 if($rowdata) ?29 { ?30 $body= stristr($rowdata,"\r\n\r\n"); ?31 $body=substr($body,4,strlen($body)); ?32 return $body; ?33 } ?34 ????return false; ?35 } ?36 ?>
PHP的3种发送HTTP请求的方式
原文地址:https://www.cnblogs.com/wanglijun/p/8822671.html