Skip to content

Instantly share code, notes, and snippets.

@dominicgan
Created May 27, 2016 10:07
Show Gist options
  • Save dominicgan/2fee5f70110ee3854f8c715dcf279561 to your computer and use it in GitHub Desktop.
Save dominicgan/2fee5f70110ee3854f8c715dcf279561 to your computer and use it in GitHub Desktop.
Write a file to remote server with php ssh2
<?php
class ssh_test extends CWidget {
public function init() {
$success = false;
$sftp_host = '123.456.78.90';
$sftp_port = '22';
$sftp_fldr_prefix = '/var/www/';
$sftp_fldr_location = 'base_dir/sub_dir/';
$connection = ssh2_connect($sftp_host, $sftp_port);
$usrn = 'username';
$pw = 'password';
if (ssh2_auth_password($connection , $usrn , $pw)){
$success = true;
$sftp = ssh2_sftp($connection);
$upload_dir = 'ssh2.sftp://'.$sftp.$sftp_fldr_prefix.$sftp_fldr_location;
// create new file at time.
$file_name = 'test_'.date('Y-m-d_hms').'.txt';
$file = $upload_dir.$file_name;
$stream = fopen($file, 'w+');
// change created file permissions
ssh2_sftp_chmod($sftp, $sftp_fldr_prefix.$sftp_fldr_location.$file_name, 0755);
// get contents of file (if any)
$value = file_get_contents($file);
// append to file
$value .= 'Create test file at ('.date('Y-m-d h:m:s').').';
// Write $value to our opened file.
if (fwrite($stream, $value) === FALSE) {
echo "Cannot write to file ($file)";
exit;
}
// test if new value is actually written to file
$value2 = file_get_contents($file);
} else {
// die('Public Key Authentication Failed');
die('Authentication Failed');
}
fclose($stream);
$view_url = 'http://'.$sftp_host.'/'.$sftp_fldr_location.$file_name;
$this->render("_ssh_test", array(
'success'=>$success,
'value'=>$value2,
'file_url'=>$view_url
));
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment