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

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来