如何对包含空格的远程URL进行curl调用

时间:2014-09-18 12:56:49

标签: php curl

这个问题是我之前的question

的延续
<?php

    $remoteFile = 'http://cdn/bucket/my textfile.txt';
    $ch = curl_init($remoteFile);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //not necessary unless the file redirects (like the PHP example we're using here)
    $data = curl_exec($ch);
    print_r($data)
    curl_close($ch);
    if ($data === false) {
      echo 'cURL failed';
      exit;
    }

    $contentLength = 'unknown';
    $status = 'unknown';
    if (preg_match('/^HTTP\/1\.[01] (\d\d\d)/', $data, $matches)) {
      $status = (int)$matches[1];
    }
    if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
      $contentLength = (int)$matches[1];
    }

    echo 'HTTP Status: ' . $status . "\n";
    echo 'Content-Length: ' . $contentLength;
    ?>

我正在使用上面的代码从CDN url获取服务器端的文件大小,但是当我使用带有空格的CDN网址时。它正在抛出错误

page not found  09/18/2014 - 16:54  http://cdn/bucket/my textfile.txt

我可以为包含空格的远程网址调用curl吗?

  

在此

上提供更多信息      

我有一个界面,用户将文件保存到CDN(所以用户   可以提供用户想要的任何标题,它可以包含空格)和所有   保存在后端db中的信息。我有另一个界面   检索保存的信息并将其与文件一起显示在我的页面中   我在上面的代码中使用的大小。

2 个答案:

答案 0 :(得分:1)

您必须对您的网址进行编码,其中包含空格。

echo urlencode('http://cdn/bucket/my textfile.txt');

参考:urlencode

或者你可以使用,

echo '<a href="http://example.com/department_list_script/',
rawurlencode('sales and marketing/Miami'), '">';

参考:rawurlencode

答案 1 :(得分:0)

是的,您需要URL / URI编码

在已编码的网址中,空格编码为:%20,因此您的网址为:http://cdn/bucket/my%20textfile.txt,因此您可以使用此网址。

或者因为这是PHP,你可以使用urlencode函数。 参考:http://php.net/manual/en/function.urlencode.php

e.g。

$ remoteFile = urlencode(&#39; http://cdn/bucket/my textfile.txt&#39;);

$ ch = curl_init(urlencode($ remoteFile));

相关问题