JasonDavis
JasonDavis

Reputation: 48983

PHP cURL does not work when calling multiple URLs?

I am trying to take a list of URL's from a textbox, it has 1 URL per line and each URL does a redirect, I am trying to get the URL that it redirects to.

When I run this code below on a single URL, it returns the redirected URL which is what I want...

function getRedirect($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
    $result = curl_exec($ch);
    $info = curl_getinfo($ch); //Some information on the fetch
    curl_close($ch);

    echo '<pre>';
    print_r($info);
    echo '</pre>';

}

$url = 'http://www.domain.com/go?a:aHR0cDovL2xldGl0Yml0Lm5ldC9kb3d';
getRedirect($url);

Now my problem is when I try to run it on multiple URL's with this code...

if(isset($_POST['urls'])){
    $rawUrls = explode("\n", $_POST['urls']);

    foreach ($rawUrls as $url) {
        getRedirect($url);
    }
}

When I run it on my list of URL's instead of giving me the redirected URL like my first example does correctly, it instead gives me the URL that I passed into cURL.

Can someone help me figure out why or how to fix this please?

Upvotes: 0

Views: 764

Answers (1)

Ben
Ben

Reputation: 21249

It's already covered in the question comments but it seems the problem would be extra spacing at the end of the url.

Calling getRedirect(trim($url)) would fix it.

The space at the end is most likely turned into a querystring space (aka %20) and changes the value of query string parameters

Upvotes: 1

Related Questions