dongwen5351 2017-05-24 18:05
浏览 35
已采纳

简单的cURL无法正常工作

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

  • 写回答

1条回答 默认 最新

  • dozabg1616 2017-05-24 18:09
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!