获取远程文件的上次修改日期

Mar*_*nry 32 php jquery curl

我想通过curl获取远程文件的最后修改日期.有谁知道这是怎么做到的吗?

Tom*_*igh 41

您可以使用curl_getinfo()以下方法执行以下操作:

<?php
$curl = curl_init('http://www.example.com/filename.txt');

//don't fetch the actual page, you only want headers
curl_setopt($curl, CURLOPT_NOBODY, true);

//stop it from outputting stuff to stdout
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

// attempt to retrieve the modification date
curl_setopt($curl, CURLOPT_FILETIME, true);

$result = curl_exec($curl);

if ($result === false) {
    die (curl_error($curl)); 
}

$timestamp = curl_getinfo($curl, CURLINFO_FILETIME);
if ($timestamp != -1) { //otherwise unknown
    echo date("Y-m-d H:i:s", $timestamp); //etc
} 
Run Code Online (Sandbox Code Playgroud)


小智 23

在PHP中,您可以使用本机函数get_headers():

<?php
$h = get_headers($url, 1);

$dt = NULL;
if (!($h || strstr($h[0], '200') === FALSE)) {
    $dt = new \DateTime($h['Last-Modified']);//php 5.3
}
Run Code Online (Sandbox Code Playgroud)

  • "如果"条件不能正常工作......`if(!$ h || strpos($ h [0],'200')!== false){`对我来说效果更好! (7认同)
  • 可能想要将Pons中的小写代码组合并添加到此.`如果(用strtolower(修剪($ K))== '最后修改')` (2认同)

Dan*_*tti 13

来自php的文章:

<?php
// outputs e.g.  somefile.txt was last modified: December 29 2002 22:16:23.

$filename = 'somefile.txt';
if (file_exists($filename)) {
    echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}
?>
Run Code Online (Sandbox Code Playgroud)

filemtime()是这里的关键.但我不确定您是否可以获取远程文件的最后修改日期,因为服务器应该将其发送给您...也许在HTTP标头中?

  • 根据我的经验,这种方法总是不起作用(它依赖于你的php.ini)所以本机get_headers对我来说效果更好. (3认同)
  • 这对远程URL不起作用(我在PHP 5.4.25中试过) (3认同)
  • 从手册:"从PHP 5.0.0开始,此函数也可以与*some*URL包装器一起使用." (2认同)