PHP class for SFTP Connection and file operation, set email on various steps to debug
{
private $connection;
private $sftp;
var $headers = “MIME-Version: 1.0\r\nContent-type: text/html; charset=iso-8859-1\r\nTo: Tarun <name@mydomain.com>\r\nFrom: <admin@mydomain.com>\r\n”;
public function __construct ($host, $port=22)
{
$message = “Connectivity started”;
$subject = “This is to confirm that the connectivity started but not done”;
//mail ($this->to, $subject, $message, $this->headers);
$this->connection = ssh2_connect ($host, $port);
if (! $this->connection)
{
$message = “Connectivity done”;
$subject = “Could not connect to $host on port $port.”;
//mail ($this->to, $subject, $message, $this->headers);
throw new Exception (“Could not connect to $host on port $port.”);
}
else
{
$message = “Connectivity Success”;
$subject = “success connect to $host on port $port.”;
mail ($this->to, $subject, $message, $this->headers);
}
//mail($this->to, “test”, “Test “, $this->headers);
}
public function login ($username, $password)
{
if (! @ssh2_auth_password ($this->connection, $username, $password))
{
$message = “Could not authenticate with username $username ” .
“and password $password.”;
$subject = “connection error”;
//mail ($this->to, $subject, $message, $this->headers);
throw new Exception (“Could not authenticate with username $username ” .
“and password $password.”);
}
$this->sftp = @ssh2_sftp ($this->connection);
if (! $this->sftp)
{
$message = “Could not initialize SFTP subsystem.”;
$subject = “initialization error”;
//mail ($this->to, $subject, $message, $this->headers);
throw new Exception(“Could not initialize SFTP subsystem.”);
}
}
public function createFile ($newfilepath)
{
$sftp = $this->sftp;
@ssh2_sftp_mkdir ($sftp, $newfilepath);
}
public function uploadFile ($local_file, $remote_file)
{
$sftp = $this->sftp;
$stream = fopen (“ssh2.sftp://$sftp$remote_file”, ‘w+’);
if (! $stream)
{
$message = “Could not open file: $remote_file”;
$subject = “error1″;
//mail ($this->to, $subject, $message, $this->headers);
throw new Exception (“Could not open file: $remote_file”);
}
$data_to_send = @file_get_contents ($local_file);
if ($data_to_send === false)
{
$message = “Could not open local file: $local_file”;
$subject = “error2″;
//mail ($this->to, $subject, $message, $this->headers);
throw new Exception (“Could not open local file: $local_file.”);
}
if (@fwrite ($stream, $data_to_send) === false)
{
$message = “Could not send data from file: $local_file”;
$subject = “error3″;
mail ($this->to, $subject, $message, $this->headers);
throw new Exception (“Could not send data from file: $local_file.”);
}
else
{
$message = “File transferd success”;
$subject = “correct”;
//mail ($this->to, $subject, $message, $this->headers);
}
@fclose ($stream);
return $success;
}
}
Checkout various functions…
