PHP 模拟发送http 请求的三种方式

1. curl

PHP默认是不支持curl功能的,因此如果要用curl的话,首先需要在php.ini中开启该功能
去掉 ;extension= php_curl.dll 前面的分号

curl 相对于 file_get_content 读取远程文件 更稳定,效率更高,功能更全。

下面是个极其简单的例子:

$request_url = 'http://www.google.com';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);
curl_setopt($ch, CURLOPT_REFERER,_REFERER_);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$r = curl_exec($ch);
curl_close($ch);
return $r;

2. file_get_content

file_get_content PHP手册
典型使用方式 stream_context_create 流式


<?php
$data = array(
	'id'=>'10000', 
	'name'=>'jack'
); 
	
$postdata = http_build_query($data);
$options = array(
	'http' => array(
		'method' => 'POST',
       'header' => array(
            "Content-type:application/x-www-form-urlencoded",
            "Contnet-length:".strlen($query_string)
            ),
		'content' => $postdata 
		//'timeout' => 60 * 60 // 超时时间(单位:s)
	)
);
 
$url = "http://www.mydomain.com/index.php";
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
 
echo $result;
?>

index.php

<?php 
$data = $_POST;
echo '<pre>';
print_r( $data );
echo '</pre>';
?

打印出post数据

3. fsocket

PHP手册
面向更底层协议,TCP/UDP 功能全面,学习成本较高

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值