Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last modified date of a remote file

Tags:

jquery

php

curl

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

like image 622
Mark Henry Avatar asked May 10 '09 12:05

Mark Henry


People also ask

How do I find the last modified date of a file?

The lastModified() method of the File class returns the last modified time of the file/directory represented by the current File object. You can get the last modified time of a particular file using this method.

How do you check the last time a file was modified in Linux?

The syntax is pretty simple; just run the stat command followed by the file's name whose last modification date you want to know, as shown in the example below. As you can see, the output shows more information than previous commands.

Which function is used for seeing last time modification of a file?

The filemtime() function is an inbuilt function that returns the last modification of the file content.


3 Answers

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
} 
like image 152
Tom Haigh Avatar answered Oct 19 '22 04:10

Tom Haigh


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
}
like image 25
h4kuna Avatar answered Oct 19 '22 03:10

h4kuna


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?

like image 14
Daniel Sorichetti Avatar answered Oct 19 '22 05:10

Daniel Sorichetti