PHP中使用CURL向,某个地址或服务器发送POST和GET请求 并获取返回值

首先新建一个PHP文件 来做出 链接测试

<?php 
 
   $ch = curl_init(); //创建了一个curl会话资源,成功返回一个句柄;

   curl_setopt($ch, CURLOPT_URL, "baidu.com"); 

   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //这是设置是否将响应结果存入变量,1是存入,0是直接echo出;

   $output = curl_exec($ch); //执行,然后将响应结果存入变量,供下面echo;


    echo $output;//关闭这个curl会话资源。
   curl_close($ch);      
?>

然后是通过GET请求

/通过curl进行GET请求的案例
<?php 
    // create curl resource 
   $ch = curl_init(); 

   // set url 
   curl_setopt($ch, CURLOPT_URL, "https://github.com/search?q=react"); 

   //return the transfer as a string 
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

   // $output contains the output string 
   $output = curl_exec($ch); 

   //echo output
   echo $output;

   // close curl resource to free up system resources 
   curl_close($ch);      
?>

然后采用POST请求

<?php 
    $data=array(
    "name" => "Lei",
    "msg" => "Are you OK?"
    );

    $ch = curl_init(); 

    curl_setopt($ch, CURLOPT_URL, "http://测试服务器的IP马赛克/testRespond.php"); 
    curl_setopt($ch, CURLOPT_POST, 1);
    //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); 
    curl_setopt($ch, CURLOPT_POSTFIELDS , http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

    $output = curl_exec($ch); 

    echo $output;

    curl_close($ch);      
?>

这里我们是构造了一个数组作为POST数据传给服务器:

  • curl_setopt($ch, CURLOPT_POST, 1)表明是POST请求;

  • curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60)设置一个最长的可忍受的连接时间,秒为单位,总不能一直等下去变成木乃伊吧;

  • curl_setopt($ch, CURLOPT_POSTFIELDS , http_build_query($data))设置POST的数据域,因为这里是数组数据形式的(等会来讲json格式),所以用http_build_query处理一下。

对于json数据呢,又怎么进行POST请求呢?

<?php 
    $data='{"name":"Lei","msg":"Are you OK?"}';

    $ch = curl_init(); 

    curl_setopt($ch, CURLOPT_URL, "http://测试服务器的IP马赛克/testRespond.php"); 
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length:' . strlen($data)));
    curl_setopt($ch, CURLOPT_POSTFIELDS , $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

    $output = curl_exec($ch); 

    echo $output;

    curl_close($ch);      
?>
传输文件

同样远程服务器端我们先传好一个接收脚本,接收图片并且保存到本地,注意文件和文件夹权限问题,需要有写入权限:

<?php
    if($_FILES){
        $filename = $_FILES['upload']['name'];
          $tmpname = $_FILES['upload']['tmp_name'];
          //保存图片到当前脚本所在目录
          if(move_uploaded_file($tmpname,dirname(__FILE__).'/'.$filename)){
            echo ('上传成功');
          }
    }
?>

然后我们再来写我们本地服务器的php curl部分:

<?php 
    $data = array('name'=>'boy', "upload"=>"@boy.png");

    $ch = curl_init(); 

    curl_setopt($ch, CURLOPT_URL, "http://远程服务器地址马赛克/testRespond.php"); 
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); 
    curl_setopt($ch, CURLOPT_POSTFIELDS , $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

    $output = curl_exec($ch); 

    echo $output;

    curl_close($ch);         
?>

浏览器中运行一下,什么都米有,去看一眼远程的服务器,还是什么都没有,并没有上传成功。

为什么会这样呢?上面的代码应该是大家搜索curl php POST图片最常见的代码,这是因为我现在用的是PHP5.6以上版本,@符号在PHP5.6之后就弃用了,PHP5.3依旧可以用,所以有些同学发现能执行啊,有些发现不能执行,大抵是因为PHP版本的不同,而且curl在这两版本中实现是不兼容的,上面是PHP5.3的实现。

下面来讲PHP5.6及以后的实现,:

<?php 
    $data = array('name'=>'boy', "upload"=>"");
    $ch = curl_init(); 

    $data['upload']=new CURLFile(realpath(getcwd().'/boy.png'));

    curl_setopt($ch, CURLOPT_URL, "http://115.29.247.189/test/testRespond.php");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); 
    curl_setopt($ch, CURLOPT_POSTFIELDS , $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

    $output = curl_exec($ch); 

    echo $output;

    curl_close($ch);         
?>

这里引入了一个CURLFile对象进行实现,关于此的具体可查阅文档进行了解。这时候再去远程服务器目录下看看,发现有了一张图片了,而且确实是我们刚才上传的图片。

远程抓取图片

<?php 
    $ch = curl_init(); 

    $fp=fopen('./girl.jpg', 'w');

    curl_setopt($ch, CURLOPT_URL, "http://远程服务器地址马赛克/girl.jpg"); 
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); 
    curl_setopt($ch, CURLOPT_FILE, $fp); 

    $output = curl_exec($ch); 
    $info = curl_getinfo($ch);

    fclose($fp);

    $size = filesize("./girl.jpg");
    if ($size != $info['size_download']) {
        echo "下载的数据不完整,请重新下载";
    } else {
        echo "下载数据完整";
    }

    curl_close($ch);    
?>

现在,在我们当前目录下就有了一张刚拿到的照片啦,是不是很激动呢!

这里值得一说的是curl_getinfo方法,这是一个获取本次请求相关信息的方法,对于调试很有帮助,要善用。

这个时候呢,服务器的家长说这个我们女儿还太小,不能找对象,就将她女儿关了起来,并且上了一个密码锁,所谓的HTTP认证,服务器呢偷偷托信鸽将HTTP认证的用户名和密码给了你,要你去见她,带她私奔。

那么拿到了用户名和密码,我们怎么通过PHP CURL搞定HTTP认证呢?

PS:这里偷懒就不去搭HTTP认证去试了,直接放一段代码,我们分析下。

function curl_auth($url,$user,$passwd){
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_USERPWD => $user.':'.$passwd,
        CURLOPT_URL     => $url,
        CURLOPT_RETURNTRANSFER => true
    ]);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

$authurl = 'http://要请求HTTP认证的地址';

echo curl_auth($authurl,'vace','passwd');
这里有一个地方比较有意思:
curl_setopt_array 这个方法可以通过数组一次性地设置多个参数,防止有些需要多处设置的出现密密麻麻的 curl_setopt方法

这时你成功见到了服务器妹子,想带她私奔,但是无奈没有盘缠走不远,服务器妹子说,她妈服务器上有金库,可以登陆上去搞一点下来。

首先我们先来分析一下,这个事情分两步,一是去登陆界面通过账号密码登陆,然后获取cookie,二是去利用cookie模拟登陆到信息页面获取信息,大致的框架是这样的。

<?php 
  //设置post的数据  
  $post = array ( 
    'email' => '账户', 
    'pwd' => '密码'
  ); 
  //登录地址  
  $url = "登陆地址";  
  //设置cookie保存路径  
  $cookie = dirname(__FILE__) . '/cookie.txt';  
  //登录后要获取信息的地址  
  $url2 = "登陆后要获取信息的地址";  
  //模拟登录 
  login_post($url, $cookie, $post);  
  //获取登录页的信息  
  $content = get_content($url2, $cookie);  
  //删除cookie文件 
  @ unlink($cookie);
     
  var_dump($content);    
?>

然后我们思考下下面两个方法的实现:

  • login_post($url, $cookie, $post)

  • get_content($url2, $cookie)

//模拟登录  
function login_post($url, $cookie, $post) { 
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 0);
    curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
    curl_exec($curl); 
    curl_close($curl);
} 
//登录成功后获取数据  
function get_content($url, $cookie) { 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie); 
    $rs = curl_exec($ch); 
    curl_close($ch); 
    return $rs; 
} 




猜你喜欢

转载自blog.csdn.net/coreyc/article/details/80308721