Get the last modified date of a remote file

前端 未结 8 2068
难免孤独
难免孤独 2020-11-29 02:45

I would like to get the last modified date of a remote file by means of curl. Does anyone know how to do that?

相关标签:
8条回答
  • 2020-11-29 02:50

    You could probably do something like this using 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
    } 
    
    0 讨论(0)
  • 2020-11-29 02:59

    From php's article:

    <?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() is the key here. But I'm not sure if you can get the last modified date of a remote file, since the server should send it to you... Maybe in the HTTP headers?

    0 讨论(0)
  • 2020-11-29 03:01

    Sometimes header come with different upper lower case, this should help:

    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;
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-29 03:07

    You can activate receiving the headers of the reply with curl_setopt($handle, CURLOPT_HEADER, true). You can also turn on CURLOPT_NOBODY to only receive the headers, and after that explode the result by \r\n and interpret the single headers. The header Last-Modified is the one that you are interested in.

    0 讨论(0)
  • 2020-11-29 03:07

    By editing h4kuna's answer I created this:

    $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>';
    
    0 讨论(0)
  • 2020-11-29 03:11

    In PHP you can use the native function 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
    }
    
    0 讨论(0)
提交回复
热议问题