I'm building a plugin that requires a database file which is updated monthly. I would like to write a function that automatically replaces the old file once every 30 days.
Here's what I have so far. Am I on the right track?
add_action( 'plugins_loaded', 'update_some_file' );
function update_some_file() {
$remotefile = curl_init('http://www.somesite.com/somefile.dat');
curl_setopt($remotefile, CURLOPT_NOBODY, true);
curl_setopt($remotefile, CURLOPT_RETURNTRANSFER, true);
curl_setopt($remotefile, CURLOPT_FILETIME, true);
$result = curl_exec($remotefile);
if ($result === false) {
die (curl_error($remotefile));
}
$timestamp_r = curl_getinfo($remotefile, CURLINFO_FILETIME);
$localfile = '/path/to/somefile.dat';
if ( file_exists( $localfile ) && ( date("Y-m-d H:i:s", $timestamp_r) - date("Y-m-d H:i:s", filemtime($localfile)) >= 30 days ) ) { // obviously need some help here.
rename('/path/to/somefile.dat', '/path/to/old_somefile.dat');
$newfile = file_get_contents('http://www.somesite.com/somefile.dat');
file_put_contents('/path/to/somefile.dat', $newfile);
unlink('/path/to/old_somefile.dat')
}
}
Or is there a simpler/better way to do this?
UPDATE:
I verified the file manipulation part is working:
add_action( 'plugins_loaded', 'update_some_file' );
function update_some_file() {
$localfile = dirname( __FILE__ ) . '/includes/localfile.txt';
if ( file_exists( $localfile ) ) {
rename(dirname( __FILE__ ) . '/includes/localfile.txt', dirname( __FILE__ ) . '/includes/old/localfile.txt');
$newfile = file_get_contents('http://somesite.com/localfile.txt');
file_put_contents(dirname( __FILE__ ) . '/includes/localfile.txt', $newfile);
unlink(dirname( __FILE__ ) . '/includes/old/localfile.txt');
}
}
UPDATE:
Here's the the final working code thanks to fischi's help. (I set the schedule to 5 mins to test it)
add_filter( 'cron_schedules', 'lsmicron_add_intervals');
function lsmicron_add_intervals( $schedules ) {
$schedules['fiveminutes'] = array(
'interval' => 300,
'display' => __('5 Minutes')
);
return $schedules;
}
add_action('lsmicron_fiveminutes_event', 'lsmi_geoip_update');
if ( !wp_next_scheduled( 'lsmicron_fiveminutes_event' ) ) {
wp_schedule_event( time(), 'fiveminutes', 'lsmicron_fiveminutes_event' );
}
function lsmi_geoip_update() {
$localfile = dirname( __FILE__ ) . '/includes/localfile.txt';
if ( file_exists( $localfile ) ) {
rename(dirname( __FILE__ ) . '/includes/localfile.txt', dirname( __FILE__ ) . '/includes/old/localfile.txt');
$newfile = file_get_contents('http://example.com/localfile.txt');
file_put_contents(dirname( __FILE__ ) . '/includes/localfile.txt', $newfile);
unlink(dirname( __FILE__ ) . '/includes/old/localfile.txt');
}
}