Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect Using cURL?

Tags:

php

I'm trying to perform a redirect using cURL. I can load the page fine, that's not a problem, but if I load say google.com non of the images load and the site does not work (obviously because its just printing the HTML and not actually doing a redirect).

Is there any way to perform a redirect using cURL? Sort of similar to how ...

header("Location: http://google.com");

... works?

Any help would be much appreciated.

like image 917
Jamie Redmond Avatar asked Jan 29 '26 06:01

Jamie Redmond


2 Answers

Well, from my understading, it seems like OP want's to redirect the user to the search results URL. Using the GoogleAPI would be a first choice and to achieve something like that, I would do this:

<?php

$query = "firefox";
$apiUrl = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=".urlencode($query);

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $apiUrl);
$content = curl_exec($ch);      

$content = json_decode($content);

$luckyUrl = $content->responseData->results[0]->unescapedUrl;



header("Location: ".$luckyUrl);
?>

The code above works like 'I feel lucky'....

like image 172
Repox Avatar answered Jan 31 '26 21:01

Repox


Use curl with -L

   -L/--location
          (HTTP/HTTPS)  If  the server reports that the requested page has
          moved to a different location (indicated with a Location: header
          and  a  3XX  response code), this option will make curl redo the
          request on the new place. If used together with -i/--include  or
          -I/--head,  headers from all requested pages will be shown. When
          authentication is used, curl only sends its credentials  to  the
          initial  host.  If a redirect takes curl to a different host, it
          won't be able to intercept the user+password. See  also  --loca‐
          tion-trusted  on how to change this. You can limit the amount of
          redirects to follow by using the --max-redirs option.

          When curl follows a redirect and the request is not a plain  GET
          (for example POST or PUT), it will do the following request with
          a GET if the HTTP response was 301, 302, or 303. If the response
          code  was  any  other  3xx code, curl will re-send the following
          request using the same unmodified method.

So when using cURL add

  curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);  
like image 24
nerkn Avatar answered Jan 31 '26 20:01

nerkn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!