Server requets through php

In development process a need sometimes arises to realize actions/commands for which there are not enough rights or access to some directories is absent for a user whose server launched and executes Drupal. Way out of the situation is library libssh2 that provides access to resources (shell) of remote server using encrypted connection.

Shell is interpreter of operating system commands.

In order to use shell commands in php, it's necessary to know: port, host, user name, password. To connect server ssh2_connect function is used, to authorize user - ssh2_auth_password.

<?php
$port   
2002;
$server 'example.com';
$login  'user@example.com';
$pass   '12345';
if (!
function_exists("ssh2_connect")) {
 exit(
"ssh2_connect disable");
}
if(!(
$con ssh2_connect($server$port))){ 
//variable $con in case of successful connection
//link of indicator of SSH connection is assigned, 
//needed later for launching ssh2_auth_password function, 
//in case of false connection FALSE value is assigned.
  
exit("could not connect to {$server} with port {$port}");
}
if(!
ssh2_auth_password($con$login$pass)) {
 exit(
"login/password is incorrect");
}
?>

There are also the following ways of authorization:

For example, after connection is set up, the following sftp functions become available:

And that's not the complete list.

<?php
$sftp 
ssh2_sftp($con);
ssh2_sftp_mkdir($sftp'/new_directory');
ssh2_sftp_rmdir($sftp'/old_directory');
?>

The most functional is ssh2_exec function that gives possibility to execute available on serer shell commands for the given user.

<?php
if (!(ssh2_exec($con"rm {$file}" ))) {
 exit(
"remove file failed");
}  
if (!(
ssh2_exec($con"cp {$path_from} {$path_to}" ))) {
 exit(
"file copy failed");
}
?>

The given library allows to use shell commands in php code that expands the opportunities for development.

Tags:
libssh2, PHP, shell