【问题标题】:curl post into a remote server [duplicate]卷曲发布到远程服务器[重复]
【发布时间】:2013-03-08 05:02:20
【问题描述】:

我对 curl 的概念和想法不熟悉。我想将以下值发布到远程服务器 https://example.com/test/token。值为 client_secret=sk_test_dndkFknKdtMLhv0eA8OdcgW1 ,code=GH_Dgl12 ,grant_type=dsfgsdK。 我该怎么做?

【问题讨论】:

    标签: php curl


    【解决方案1】:

    带有参数的 curl 帖子的简单示例:

    <?php
    //
    // A very simple PHP example that sends a HTTP POST to a remote site
    //
    
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL,"http://www.mysite.com/tester.phtml");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,
            "client_secret=sk_test_dndkFknKdtMLhv0eA8OdcgW1, code=GH_Dgl12, grant_type=dsfgsdK");
    
    // receive server response ...
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $server_output = curl_exec ($ch);
    
    curl_close ($ch);
    
    // further processing ....
    if ($server_output == "OK") { ... } else { ... }
    
    ?>
    

    选项 CURLOPT_RETURNTRANSFER 将使 curl_exec() 返回响应,以便您也可以捕获它。

    【讨论】:

      【解决方案2】:
      $url = 'http://domain.com/get-post.php';
      $fields = array(
                  'client_secret' => urlencode('sk_test_dndkFknKdtMLhv0eA8OdcgW1'),
                  'code' => urlencode('GH_Dgl12'),
                  'grant_type' => urlencode('dsfgsdK'),
              );
      
      //url-ify the data for the POST
      foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
      rtrim($fields_string, '&');
      
      //open connection
      $ch = curl_init();
      
      //set the url, number of POST vars, POST data
      curl_setopt($ch,CURLOPT_URL, $url);
      curl_setopt($ch,CURLOPT_POST, count($fields));
      curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
      
      //execute post
      $result = curl_exec($ch);
      
      //close connection
      curl_close($ch);
      

      【讨论】:

      • 非常感谢 shaddy..我可以从该服务器获取响应吗?
      • 是的,你可以设置 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);就在调用 curl_exec 之前。然后响应将分配给 $result :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-08
      • 2014-06-29
      • 2019-08-04
      相关资源
      最近更新 更多