是否可以使用一个功能打开一个套接字,并使用同一页面中的另一个函数向该套接字发送命令?
当我尝试这个时,我得到:Warning: fputs(): supplied argument is not a valid stream resource
这是我正在使用的代码
connect();
cmd("cd /home/tom\n ls\n");
close();
function connect () {
global $passwd;
if (!$fp = @fsockopen("127.0.0.1", 23, $errno, $errstr, 5)) {
exit('Login Failed');
}
stream_set_timeout($fp, 1);
fputs($fp, "tom\n"); sleep(1);
fputs($fp, "$passwd\n"); sleep(1);
$res = fread($fp,1024);
var_dump($res);
}
function cmd ($cmd) {
global $fp;
fputs($fp, $cmd); sleep(1);
$res = fread($fp,1024);
var_dump($res);
}
function close () {
global $fp;
fclose($fp);
}
知道如何让它发挥作用吗? 感谢
答案 0 :(得分:0)
您需要全局存储指针或通过引用传递它。
这是一种方法
$fp = connect($passwd);
cmd($fp, "cd /home/tom\n ls\n");
close($fp);
function connect ($passwd) {
if (!$fp = @fsockopen("127.0.0.1", 23, $errno, $errstr, 5)) {
exit('Login Failed');
}
stream_set_timeout($fp, 1);
fputs($fp, "tom\n"); sleep(1);
fputs($fp, "$passwd\n"); sleep(1);
$res = fread($fp,1024);
var_dump($res);
return $fp;
}
function cmd ($fp, $cmd) {
fputs($fp, $cmd); sleep(1);
$res = fread($fp,1024);
var_dump($res);
}
function close ($fp) {
fclose($fp);
}
我不确定此代码的生存环境,因此很难提出不同或更好的策略。我可能会这样做面向我的自我:
$command = new Command($passwd);
if($command->connect()){
$res = $command->cmd("cd /home/tom\n ls\n");
// Use $result of cmd() here
$command->close(); // close when done
}
class Command {
private $fp;
private $passwd;
public function __construct($passwd) {
$this->passwd = $passwd;
}
public function connect () {
if (!$p = @fsockopen("127.0.0.1", 23, $errno, $errstr, 5)) {
return false; // Or throw an exception
}
stream_set_timeout($fp, 1);
fputs($fp, "tom\n"); sleep(1);
fputs($fp, "$passwd\n"); sleep(1);
$res = fread($fp,1024);
var_dump($res);
$this->fp = $fp;
return true; // Or $res if you want to use it somewhere else
}
function cmd ($cmd) {
$fp = $this->fp;
fputs($fp, $cmd); sleep(1);
$res = fread($fp,1024);
var_dump($res);
return $res; // if you want to use it else where
}
function close () {
fclose($this->fp);
}
}