file_get_content的get和post请求

上下文选项

介绍:

PHP提供了多种上下文选项和参数,可用于所有的文件系统或数据流封装协议。上下文由 stream_context_create()创建。选项可通过stream_context_set_option()设置,参数可用stream_context_set_params()设置。

多种上下文:(请参考php手册)
这里写图片描述
获取上下文:

//http上下文
$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);
$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);
$context = stream_context_create($opts);
//socket 上下文
// connect to the internet using the '192.168.0.100' IP and port '7000'
$opts = array(
    'socket' => array(
        'bindto' => '192.168.0.100:7000',
    ),
);
// create the context...
$context = stream_context_create($opts);
...

file_get_content 的 get 请求:

<?php
/**
 * GET 请求
 * @param  [string] $url      请求链接
 * @param  [string] $method   请求方法
 * @param  [array] $get_data 携带的参数
 * @return [array] $result    返回获取的内容
 */
function send_get($url,$method, $get_data) {

      $getdata = http_build_query($get_data);
      $options = array(
            'http' => array(
                'method' => 'GET',
                'header' => 'Content-type:application/x-www-form-urlencoded',
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url.$getdata, false, $context);
        return $result;
}

$get_data = array(

    'username' => 'username',
    'password' => 'password'
);
$res =send_get('http://www.test.com/index.php?name=act',$get_data);
var_dump($res);
die;

file_get_content 的 post 请求:

<?php
/**
 * POST 请求
 * @param  [string] $url      请求链接
 * @param  [array] $post_data 携带的参数
 * @return [array] $result    返回获取的内容
 */
function send_post($url,$post_data) {

      $postdata = http_build_query($post_data);
      $options = array(
            'http' => array(
                'method' => 'POST',//注意要大写
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
}

$post_data = array(

    'username' => 'username',
    'password' => 'password'
);
$res =send_post('http://www.test.com/index.php?name=act',$post_data);
var_dump($res);
die;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值