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:
- ssh2_auth_hostbased_file - authorization using public HOSTKEY;
- ssh2_auth_none - authorization using "none" method, which is usually not available;
- ssh2_auth_pubkey_file - authorization using public key.
For example, after connection is set up, the following sftp functions become available:
- ssh2_sftp_mkdir - creating directories;
- ssh2_sftp_rename - renaming remote files;
- ssh2_sftp_rmdir - deleting directories;
- ssh2_sftp_unlink - deleting files;
- ssh2_sftp - initialization of subsystem SFTP with already connected server SSH2;
- ssh2_sftp_realpath - transforms file name into real effective path at remote file system.
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.


