【问题标题】:How do I translate this command line curl into php curl?如何将此命令行 curl 转换为 php curl?
【发布时间】:2012-05-10 20:21:24
【问题描述】:

我有一段命令行 curl 代码,我想将其翻译成 php。我在挣扎。

这是代码行

$ curl -H "Authorization: 622cee5f8c99c81e87614e9efc63eddb" https://api.service.com/member

大字符串将是我要传递给它的变量。

这在 PHP 中是什么样子的?

【问题讨论】:

    标签: php curl command-line command


    【解决方案1】:

    您首先需要分析该行的作用:

    $ curl -H "Authorization: 622cee5f8c99c81e87614e9efc63eddb" https://api.service.com/member
    

    这并不复杂,你可以在curl's manpage找到所有开关的解释:

    -H, --header <header>: (HTTP) 获取网页时使用的额外标头。您可以指定任意数量的额外标头。 [...]

    您可以在 PHP 中通过curl_setopt_arrayDocs 添加标题(所有可用选项在curl_setoptDocs 中进行了说明):

    $ch = curl_init('https://api.service.com/member');
    // set URL and other appropriate options
    $options = array(        
        CURLOPT_HEADER => false,
        CURLOPT_HTTPHEADER => array("Authorization: 622cee5f8c99c81e87614e9efc63eddb"),
    );
    curl_setopt_array($ch, $options);
    curl_exec($ch); // grab URL and pass it to the browser
    curl_close($ch);
    

    如果 curl 被阻止,您也可以使用 PHP 的 HTTP 功能来执行此操作,即使 curl 不可用(如果 curl 在内部可用,则需要 curl):

    $options = array('http' => array(
        'header' => array("Authorization: 622cee5f8c99c81e87614e9efc63eddb"),
    ));
    $context = stream_context_create($options);
    $result = file_get_contents('https://api.service.com/member', 0, $context);
    

    【讨论】:

      【解决方案2】:

      1) 你可以使用Curl functions

      2) 你可以使用exec()

      exec('curl -H "Authorization: 622cee5f8c99c81e87614e9efc63eddb" https://api.service.com/member');
      

      3) 如果您只想将信息作为字符串,则可以使用file_get_contents()...

      <?php
      // Create a stream
      $opts = array(
        'http'=>array(
          'method'=>"GET",
          'header'=>"Authorization: 622cee5f8c99c81e87614e9efc63eddb"
        )
      );
      
      $context = stream_context_create($opts);
      
      // Open the file using the HTTP headers set above
      $file = file_get_contents('https://api.service.com/member', false, $context);
      ?>
      

      【讨论】:

        【解决方案3】:

        您应该查看 php.ini 中的 curl_* 函数。 使用curl_setopt(),您可以设置请求的标头。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-06-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-01
          相关资源
          最近更新 更多