使用PHP发布到Web API的最佳方式是什么?

使用PHP发布到Web API的最佳方式是什么?

问题描述:

我见过curl()用作POST的一种方式 - 还有其他更广泛使用或更好的方法吗?使用PHP发布到Web API的最佳方式是什么?

看到incredibly huge amount of settings you have with cURL,可能没有理由使用其他任何东西。

AFAIK,cURL是PHP推荐到另一个API的推荐方式。可能还有其他的方法,但cURL内置于PHP来处理这种情况,所以为什么不使用它?

从PHP 4.3和PHP 5开始,您还可以使用stream_context_create()fopen()/file_get_contents()联合进行POST请求。

完整的POST示例是here

至于哪个更好,我从来没有见过一个PHP安装带有卷曲支持没有编译。但看到它needs an external library和流上下文方法不对,一个可以认为后者是更好的选择用于便携式应用。

CURL仍然是更灵活的工具,并且有更多的选择和功能。但是,如果只需要POST请求,我会使用内置的方式。

我最近回答了similar question,提供了一个基本的POST'able实现既file_get_contents()和卷曲的和一些基准应该帮助你决定。

已经提到cURL需要libcurl扩展,并且在某些服务器上file_get_contents()可能无法请求远程文件allow_url_fopen设置为Off

您必须选择哪一个最适合您,我通常使用以下函数,如果cURL不可用,则返回file_get_contents()

function Request($url, $post = null) 
{ 
    if (extension_loaded('curl') === true) 
    { 
     $curl = curl_init($url); 

     if (is_resource($curl) === true) 
     { 
      curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); 
      curl_setopt($curl, CURLOPT_FAILONERROR, true); 
      curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); 
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); 
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); 

      if (isset($post) === true) 
      { 
       curl_setopt($curl, CURLOPT_POST, true); 
       curl_setopt($curl, CURLOPT_POSTFIELDS, (is_array($post) === true) ? http_build_query($post, '', '&') : $post); 
      } 

      $result = curl_exec($curl); 
     } 

     curl_close($curl); 
    } 

    else 
    { 
     $http = array 
     (
      'method' => 'GET', 
      'user_agent' => $_SERVER['HTTP_USER_AGENT'], 
     ); 

     if (isset($post) === true) 
     { 
      $http['method'] = 'POST'; 
      $http['header'] = 'Content-Type: application/x-www-form-urlencoded'; 
      $http['content'] = (is_array($post) === true) ? http_build_query($post, '', '&') : $post; 
     } 

     $result = @file_get_contents($url, false, stream_context_create(array('http' => $http))); 
    } 

    return $result; 
}