0

I have code here that should return to me the source code of the webpage.

<?php
function curlGet($url){
  $ch = curl_init();

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_URL, $url);

  $results = curl_exec($ch);

  curl_close($ch);

}

$packtPage = curlGet('https://www.google.com');

print_r($packtPage);

As far as I understand this code should return and echo out the source code of that webpage. However, I get a blank page when running this code.

After searching everywhere for an understanding of why this isn't working as expected I troubleshooted and found that commenting out the following line

// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

the webpage shows

302 Moved

The document has moved here.

'here' is a link that redirects to the url that was given.

Please help me understand what's going on!!

Ben
  • 515
  • 5
  • 18

1 Answers1

4

When you use

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$results = curl_exec($ch);

You are telling PHP to "Store the output of the cURL request in the $results variable and don't output anything to the screen.

If you want to see output, modify your code as following to return the value of $results to the print_r function:

<?php
function curlGet($url){
  $ch = curl_init();

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_URL, $url);

  $results = curl_exec($ch);

  curl_close($ch);
  return $results;
}

$packtPage = curlGet('https://www.google.com');

print_r($packtPage);

As suggested by GentlemanMax in a comment, it can also be a good idea to include the following line in your cURL request. This line tells cURL to follow redirects, since you are receiving a HTTP/302 status code which means the page was moved. Curl can follow these kind of redirects using the following extra option:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
Pieter De Clercq
  • 1,951
  • 1
  • 17
  • 29
  • yes. thank you. I forgot to add the return statement at the end. But it was really the 302 redirects that was troubling me a bit. Also it was confusing that when troubleshooting instead of echo I tried var_dump or print_r and the same result was appearing. But now I understand more so thank you for the answer. It helped me in my first foray into cURL! – Ben May 24 '17 at 20:16