dsceme82487 2011-11-01 02:17
浏览 78
已采纳

Php curl:工作脚本,需要一点补充

This is my code:

    function get_remote_file_to_cache(){    
$sites_array = array("http://www.php.net", "http://www.engadget.com", "http://www.google.se", "http://arstechnica.com", "http://wired.com");
$the_site= $sites_array[rand(0, 4)];

    $curl = curl_init();
    $fp = fopen("rr.txt", "w");
    curl_setopt ($curl, CURLOPT_URL, $the_site);
    curl_setopt($curl, CURLOPT_FILE, $fp);    
    curl_exec ($curl);
    curl_close ($curl);
}    

$cache_file = 'rr.txt';
$cache_life = '15'; //caching time, in seconds    
$filemtime = @filemtime($cache_file);     

if (!$filemtime or (time() - $filemtime >= $cache_life)){
    ob_start();  

echo file_get_contents($cache_file);    
ob_get_flush();

echo " <br><br><h1>Writing to cache</h1>";
get_remote_file_to_cache(); 
}else{
   echo "<h1>Reading from cache file:</h1><br> ";    
    ob_start();    
echo file_get_contents($cache_file);
ob_get_flush();

}

Everything works as it should and no problems or surprises, and as you can see its pretty simple code but I am new to CURL and would just like to add one check to the code, but dont know how:

Is there anyway to check that the file fetched from the remote site is not a 404 (not found) page or such but is a status code 200 (successful) ?

So basically, only write to cache file if the fill is status code 200.

Thanks!

  • 写回答

2条回答 默认 最新

  • doulu6234 2011-11-01 02:32
    关注

    To get the status code from a cURL handle, use curl_getinfo after curl_exec:

    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    

    But the cached file will be overwritten when

    $fp = fopen("rr.txt", "w");
    

    is called, regardless of the HTTP code, this means that to update the cache only when status is 200, you need to read the contents into memory, or write to a temporary file. Then finally write to the real file if the status is 200.

    It is also a good idea to

    touch('rr.txt');
    

    before executing cURL, so that the next request that may come before the current operation finish will not also try to load the page to page too.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)