TAGS :Viewed: 11 - Published at: a few seconds ago

[ PHP encoding URL with cURL ]

I am trying to access an array of URLs with cURL. Some of the links look like the following:

 http://somelink.com/directory/file name.php
 http://somelink.com/file name.php
 http://somelink.com/(some file).txt
 http://somelink.com/directory/random chars &^%.txt
 http://somelink.com/!@#$%^&*.txt

Just some files with some random characters. I know there is the urlencode() function, but this function also url encodes the http:// and the / after each directory, which will not allow the page to load properly in cURL. Is there some regular expression that can be used to separate the words after each / and encode them individually, but ignore the encoding of everything before the root directory /?

Answer 1


You can write a function to take input in the format you have (array) and output it in the desired format like this:

function urlencode_array($url_array)
{
    $encoded = array();

    foreach ($url_array as $url) {
        $encoded[] = "http://" . str_replace("%2F", "/", rawurlencode(substr($url, 7)));
    }

    return $encoded;
}