tags:

views:

78

answers:

1

I'm trying to make curl follow a redirect but I can't quite get it to work right. I have a string that I want to send as a GET param to a server and get the resulting URL.


Example:
String = Kobold Vermin
Url = www.wowhead.com/search?q=Kobold+Worker

If you go to that url it will redirect you to www.wowhead.com/npc=257. I want curl to return this url to my php code so that i can extract the npc=257 and use it.


Current code:

function npcID($name) {
    $urltopost = "http://www.wowhead.com/search?q=" . $name;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1");
    curl_setopt($ch, CURLOPT_URL, $urltopost);
    curl_setopt($ch, CURLOPT_REFERER, "http://www.wowhead.com");
    curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type:application/x-www-form-urlencoded"));
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    return curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
}

This however returns www.wowhead.com/search?q=Kobold+Worker and not www.wowhead.com/npc=257.

I suspect php is returning before the external redirect happens. How can I fix this?

Thanks for your time.

+3  A: 

Erm... I don't think you're actually executing the curl... Try:

curl_exec($ch);

...after setting the options, and before the curl_getinfo() call.

EDIT: If you just want to find out where a page redirects to, I'd use the advice here, and just use Curl to grab the headers and extract the Location: header from them:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$a = curl_exec($ch);
if(preg_match('#Location: (.*)#', $a, $r))
 $l = trim($r[1]);
Matt Gibson
This makes php follow the redirect. I dont want to follow the redirect, I just want to know the url of the redirected page.
Thomas Van Nuffel
Oh, so you don't actually want to fetch the page? Just find out the location? In that case, I'd suggest the tactic used here: http://zzz.rezo.net/HowTo-Expand-Short-URLs.html -- basically just grab the header from the page that redirects, and grab the Location: header from it. Either way, though, you still need to do the exec() for Curl to actually _do_ anything...
Matt Gibson
Thanks, this worked like a charm :)
Thomas Van Nuffel