I have been trying to serialize phpseclib connection since I am loading some php pages from ajax and I dont want to reconnect again and again.
Page 1 - define SSH2 First
require("Net/SSH2.php");
session_start();
$ssh = new Net_SSH2 ("localhost");
if ($ssh->login($username, $pass)) {
$_SESSION['obj'] = serialize($ssh);
}else{
echo "Invalid Login !!!";
}
Page 2 - Get Stored session with unserialize
session_start();
require("Net/SSH2.php");
$ssh = unserialize($_SESSION['obj']);
echo $ssh->exec('ls');
I want to put Login information in $_SESSION['obj']
too so Whenever I am on that php page i just $ssh = unserialize($_SESSION['obj']);
and then $ssh->exec('pwd')
..
Is there work around or will I have to always connect/login to Net/SSH2.php whenever I am on that PHP page ???
The only way to have a persistent connection is to actually have a script constantly running which is keeping the connection open. Which means you have one script with a never ending while (true) { ... }
loop which opens a connection once and keeps it. You then need to find a way to communicate with this script to make it execute commands. AMQP, ØMQ, Gearman, sockets and similar techniques can be employed for that.
Depending on which PHP version you have, you could try to declare a static variable for the ssh connection.
If phpseclib uses pfsockopen it might be able to reuse existing connections - but that is a longshot, and might require modification of the library.
But generally speaking you cannot do what you want in PHP. When the script is finished all open sockets are closed, as the executing process terminates. You certainly can't store it in a session variable - as soon as the Net_SSH2 object goes out of scope it is destroyed.
来源:https://stackoverflow.com/questions/15361748/how-to-serialize-phpseclib