php 模拟发送post请求

使用curl和file_get_contents实现POST数据上传
本文介绍了如何使用PHP的curl和file_get_contents函数实现POST数据上传,包括设置参数、执行上传操作及返回结果处理。
1.curl实现

/*通过curl发送post数据*/
function execUpload($post_data, $url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, false);
    //启用时会发送一个常规的POST请求,类型为:application/x-www-form-urlencoded,就像表单提交的一样。
    curl_setopt($ch, CURLOPT_POST, true);  
    curl_setopt($ch,CURLOPT_BINARYTRANSFER,true);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $info= curl_exec($ch);
    curl_close($ch);
    return $info;
}

CURLOPT_RETURNTRANSFER  设为true  不直接在页面输出内容

2.file_get_contents实现

/*通过file_get_contents发送post数据*/
function postData($post_string,$url){
    $context = array(
        'http' => array(
            'method' => 'POST',
            'header' => 'Content-type: application/x-www-form-urlencoded' .'\r\n'.
                        'User-Agent : Jimmy\'s POST Example beta' .'\r\n'.
                        'Content-length:' . strlen($post_string) + 8,
            'content' => $post_string)
        );
    $stream_context = stream_context_create($context);
    $data = file_get_contents($url, false, $stream_context);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值