【发布时间】:2009-05-10 12:12:10
【问题描述】:
我想通过 curl 获取远程文件的最后修改日期。有谁知道这是怎么做到的吗?
【问题讨论】:
我想通过 curl 获取远程文件的最后修改日期。有谁知道这是怎么做到的吗?
【问题讨论】:
您可能可以使用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
}
【讨论】:
在 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
}
【讨论】:
if(!$h || strpos($h[0], '200') !== false){ 更适合我!
! 运算符。 if 语句应该是if (!(!$h || strstr($h[0], '200') === FALSE)) {
if(strtolower(trim($k))=='last-modified')
<?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));
}
?>
filemtime() 是这里的关键。但我不确定您是否可以获取 remote 文件的最后修改日期,因为服务器应该将其发送给您...也许在 HTTP 标头中?
【讨论】:
有时标题带有不同的大写小写,这应该会有所帮助:
function remoteFileData($f) {
$h = get_headers($f, 1);
if (stristr($h[0], '200')) {
foreach($h as $k=>$v) {
if(strtolower(trim($k))=="last-modified") return $v;
}
}
}
【讨论】:
您可以使用curl_setopt($handle, CURLOPT_HEADER, true) 激活接收回复的标题。您还可以打开 CURLOPT_NOBODY 以仅接收标头,然后将结果分解为 \r\n 并解释单个标头。标题Last-Modified 是您感兴趣的标题。
【讨论】:
通过编辑 h4kuna 的答案,我创建了这个:
$fileURL='http://www.yahoo.com';
$headers = get_headers($fileURL, 1);
$date = "Error";
//echo "<pre>"; print_r($headers); echo "</pre>";
if ( $headers && (strpos($headers[0],'200') !== FALSE) ) {
$time=strtotime($headers['Last-Modified']);
$date=date("d-m-Y H:i:s", $time);
}
echo 'file: <a href="'.$fileURL.'" target="_blank">'.$fileURL.'</a> (Last-Modified: '.$date.')<br>';
【讨论】:
像这样的工作,来自web developer forum
<? $last_modified = filemtime("content.php"); print("Last Updated - ");
print(date("m/d/y", $last_modified)); ?
// OR
$last_modified = filemtime(__FILE__);
该链接提供了一些有用的网站,您可以使用它们
【讨论】:
必须解决类似的问题,但对我来说每天下载一次就足够了,所以我只比较了本地(下载)缓存文件的修改日期。远程文件没有 Last-Modified 标头。
$xml = 'test.xml';
if (is_file($xml) || date('d', filemtime($xml)) != date('d')) {
$xml = file_get_contents(REMOTE_URL);
}
【讨论】: