I have three files: login.php, index.php, summary.php. All my session variables are set when user visits login.php. Below is my code snippet:
<?php
if( isset($_POST['submit']) )
{
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $username;
if(!($con = ssh2_connect('192.168.1.7', 22))){
echo "<script> alert(\"Fail: Unable to establish connection\"); </script>";
}
else {
if(!ssh2_auth_password($con, $username , $password )) {
echo "<script> alert(\"Fail: Unable to authenticate\"); </script>";
}
else {
//echo "<script> alert(\"Successfully logged in\"); </script>";
$_SESSION['con'] = $con;
header("Location: index.php");
//echo $_SESSION['con'];
}
}
}
?>
When I print my session variable $_SESSION['con']
in login.php, it prints Resource ID#1 as expected. Below is my index.php file which uses both the session variables.
<?php
session_start();
echo $_SESSION['username'];
echo $_SESSION['con'];
?>
When I print the session variables in index.php, $_SESSION['username']
gives me the correct output but $_SESSION['con']
prints 0
which was supposed to print Resource ID#1. That is, session variable con
's value has been changed to zero.
$con
is a resource, and you can't persist resources. You'll have to recreate the ssh connection every time if you need to use it.
And even if it would be possible to persist resources in your session, the ssh connection will likely become invalid at some point in the future, and you'll have to re-create it again.
The reason you can't persist resources
is because most of them (if not all) map to host system's handles
, and handles
are valid only in the context of the process
that created them. And since each PHP
request is routed to a dedicated process
(either newly created or extracted from a pool of processes), you can't use a resource
in two separate requests as its likely they'll end up being served by different processes.
There's a very good article on the PHP manual website talking about persistent database connections. It describes very well the different setups in which PHP code ends up executing, and why persistent connections have advantages/disadvantages.
I also found this SO question about making persistent ssh connections. Beside the solutions enumerated in that question, another possible one would be for you to write a daemon that keeps the ssh connection open, and reconnects in case the connection got closed. You'd then connect from your PHP script to that daemon. Note that you'll still won't save the connection to the daemon and will have to recreate it every time you need it; this is just a solution to avoid saving the username and password into the session.