Hitesh
Hitesh

Reputation: 4298

How to make curl call for remote url which contain space

This question is continuation of my previous 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;
    ?>

I am using above code to get the file size in server side from CDN url but when I use the CDN url with space in it. it is throwing below error

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

Can I make curl call for remote url which contain space ?

To give little bit more info on this

I am having interface where user will be saving file to CDN (so user can give whatever title user want, it may contain space )and all information in saved in back end db. I have another interface where I retrieve the saved information and show it in my page along with file size which I am getting using above code.

Upvotes: 1

Views: 2489

Answers (2)

developer
developer

Reputation: 728

Yes you need to URL / URI encode

In an encoded URL, the spaces are encoded as: %20, so your URL would be: http://cdn/bucket/my%20textfile.txt so you could just use this url.

Or as this is PHP, you could use the urlencode function. ref: http://php.net/manual/en/function.urlencode.php

e.g.

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

or

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

Upvotes: 0

Dhanendran
Dhanendran

Reputation: 392

You have to encode your url's which have space's in it.

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

Ref: urlencode

or you can use,

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

Ref: rawurlencode

Upvotes: 2

Related Questions