1
#!/usr/bin/php

<?php
$username = "user";
$password = "pass";
$url      = '10.168.8.666';
// Make our connection
$connection = ssh2_connect($url);

// Authenticate
if (!ssh2_auth_password($connection, $username, $password))
     {echo('Unable to connect.');}

// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection))
     {echo ('Unable to create SFTP connection.');}


$localDir  = 'file:///home/batman/Downloads/dbs';
$remoteDir = '/home/batbackup/Dropbox/dbs';
// download all the files
$files = scandir ('ssh2.sftp://' . $sftp . $remoteDir);
if (!empty($files)) {
  foreach ($files as $file) {
    if ($file != '.' && $file != '..') {
        if (substr($file, 0, 11)=='07-Jun-2017'){
            # code...
              ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");

        }

    }
  }
}
?>

I use this script to download backups from an sftp server everyday but i ve to manually change the date (in bold) in the script everyday. Question: is there a way i can make the script to change the date automatically so that i can set up a cron job?

Belgarath
  • 104
  • 12

2 Answers2

2

Replace your date with

date('d-M-Y')

http://php.net/manual/fr/function.date.php

This will take server current time.

2

Use date().

date('d-M-Y')

It will become

#!/usr/bin/php

<?php
$username = "user";
$password = "pass";
$url      = '10.168.8.666';
// Make our connection
$connection = ssh2_connect($url);

// Authenticate
if (!ssh2_auth_password($connection, $username, $password))
     {echo('Unable to connect.');}

// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection))
     {echo ('Unable to create SFTP connection.');}


$localDir  = 'file:///home/batman/Downloads/dbs';
$remoteDir = '/home/batbackup/Dropbox/dbs';
// download all the files
$files = scandir ('ssh2.sftp://' . $sftp . $remoteDir);
if (!empty($files)) {
  foreach ($files as $file) {
    if ($file != '.' && $file != '..') {

        if (substr($file, 0, 11) == date('d-M-Y')) {
            # code...
              ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");

        }

    }
  }
}
?>

If you want it to always be, let's say, yesterday, you may use it with strtotime(), so

date('d-M-Y', strtotime('yesterday'))
phaberest
  • 3,140
  • 3
  • 32
  • 40