title: Transfer files using SFTP and either PHP or shell/terminal script
body: <p>I need to write a script that is run as a cron job every night which transfers some report files via sftp to another server.</p>
  <p>The report files are created every night using another cron in the format 'support_[date].csv' &amp; 'download_[date].csv'.</p>
  <p>I'm wondering if you had any pointers on how to do the following:</p>
  <ol>
  <li>Find the 2 files created on latest [date]</li>
  <li>Copy these files to another server using SFTP</li>
  </ol>
  <p>I've tried several PHP scripts utilising the ssh2 extension, but to no avail. Is there a way to do it using a shell script? It's not something I am hugely familiar with to be honest (hence going down the PHP route initially)</p>
  <p>This was one of my PHP scripts which didn't work:</p>
  <pre><code>$src = 'test.csv';
  
  $filename = 'test.csv';
  $dest = '/destination_directory_on_server/'.$filename;
  
  $connection = ssh2_connect('example.com', 22);
  ssh2_auth_password($connection, 'username', 'password');
  
  // Create SFTP session
  $sftp = ssh2_sftp($connection);
  
  $sftpStream = fopen('ssh2.sftp://'.$sftp.$dest, 'w');
  
  try {
         
              if (!$sftpStream) {
                  throw new Exception(&quot;Could not open remote file: $dest&lt;br&gt;&quot;);
              }
             
              $data_to_send = file_get_contents($src);
             
              if ($data_to_send === false) {
                  throw new Exception(&quot;Could not open local file: $src.&lt;br&gt;&quot;);
              }
             
              if (fwrite($sftpStream, $data_to_send) === false) {
                  throw new Exception(&quot;Could not send data from file: $src.&lt;br&gt;&quot;);
              } else {
                  //Upload was successful, post-upload actions go here...
              }
             
              fclose($sftpStream);
                             
          } catch (Exception $e) {
             
              //error_log('Exception: ' . $e-&gt;getMessage());
             echo 'Exception: ' . $e-&gt;getMessage();
              if($sftpStream) {fclose($sftpStream);}
              
          }
  </code></pre>
  <p>This were the error messages I got:</p>
  <blockquote>
  <p>Warning: fopen() [function.fopen]: URL
  file-access is disabled in the server
  configuration in
  /path_to_script/sftp-test.php  on line
  17</p>
  <p>Warning: fopen(ssh2.sftp://Resource id</p>
  <h1>3/destination_directory_on_server/test.csv)</h1>
  <p>[function.fopen]: failed to open
  stream: no suitable wrapper could be
  found in /path_to_script/sftp-test.php
  on line 17 Exception: Could not open
  remote file:
  /destination_directory_on_server/test.csv</p>
  </blockquote>