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!!
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);