curl几个步骤

一:curl的基本操作

<?php
    //1.初始化curl,返回资源
    $curl = curl_init();

    //2.设置curl工具请求的服务器文件地址
    //参数1:curl资源
    //参数2:设置请求的选项
    //参数3:请求选项的值
    curl_setopt($curl,CURLOPT_URL,'http://www/baidu.com/index.php');

    //3.发出请求
    curl_exec($curl);
    
    //4.关闭curl
    curl_close($curl);

二:curl模拟post提交的方式

<?php
    //1.初始化curl,返回资源
    $ch = curl_init();

    //2.设置选项,设置请求的服务器地址
    //开启post提交
    curl_setopt($ch,CURLOPT_POST,ture);

    //设置提交什么数据过去
    $data = array('order'=>'ESC1000000012');
    curl_setopt($ch,CURLOPT_POSTFIELDS,$value);

    //设置请求的地址
    curl_setopt($ch,CURLOPT_URL,'http://localhost/3.post.handl.php');
    
    //3.发出请求
    curl_exec($ch);

    //4.关闭资源
    curl_close($ch);

三:curl的一些常用选项

(1)设置将结果返回而不是直接显示

CURLOPT_RETURNTRANSFER

<?php
    //1.初始化curl,返回资源
    $curl = curl_init();

    //2.设置curl工具请求的服务器文件地址
    //参数1:curl资源
    //参数2:设置请求的选项
    curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);//保存结果,而不展示
    curl_setopt($curl,CURLOPT_URL,'http://www/baidu.com/index.php');

    //3.发出请求
    $res = curl_exec($curl);
    var_dump($res);
    //4.关闭curl
    curl_close($curl);

(2)针对https的请求,需要验证客户端的安全证书,一般设跳过验证

CURL_SSL_VERIFYHOST,CURL_SSL_VERIFYPEER

<?php
    //1.初始化curl,返回资源
    $ch = curl_init();

    //2.设置选项,设置请求的服务器地址
    //开启post提交
    curl_setopt($ch,CURLOPT_POST,ture);

    //设置提交什么数据过去
    $data = array('order'=>'ESC1000000012');
    curl_setopt($ch,CURLOPT_POSTFIELDS,$value);

    //设置请求的地址
    curl_setopt($ch,CURLOPT_URL,'https://localhost/3.post.handl.php');
    //跳过跳过https证书验证
    curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
    curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
    //3.发出请求
    curl_exec($ch);

    //4.关闭资源
    curl_close($ch);

四:通过curl,模拟cookie登陆

<?php
    $ch = curl_init();
    $url = 'http://localhost/0402/index.php?c=user&a=doLogininAction';

    //设置发送地址,地址为登陆地址
    curl_setopt($ch,CURLOPT_URL,$url);
    $data = array(
        'user_name' => 'zhangsanfeng',
        'password' => 'admin123456'
    );

    //设置发送方式
    curl_setopt($ch,CURLOPT_POST,true);

    //设置发送数据
    curl_setopt($ch,CURLOPT_POSTFIELDS,$data);

    //获取cookie,设置我们的cookie保存到哪里:服务器要把session名字告诉你,此处为开启session时保存的sessionid
    curl_setopt($ch,CURLOPT_COOKIEJAR,'D:/cookie.txt');
    curl_exec($ch);

    curl_close($ch);

    //我们再访问index.php这个文件的时候,要随身携带cookie(保存的是session文件名)
    curl_setopt($ch,CURLOPT_URL,'http://localhost//0420/index.php');

    //设置携带的cookie
    curl_setopt($ch,CURLOPT_COOKIEFILE,'D:/cookie.txt');
    curl_exec($ch);
    curl_close($ch);

猜你喜欢

转载自blog.csdn.net/wangyingjie290107/article/details/81435710