PHP 7.4正常的SSH2 SFTP脚本在PHP 8.1中报fopen错误
PHP 8.1下SSH2扩展SFTP上传fopen失败问题
我使用以下脚本配合定时任务,将公网网站生成的XML文件通过SFTP上传至服务器。该脚本在PHP 7.4(SSH2 v1.2)中运行正常,但在PHP 8.1.16(SSH2 v1.3.1)中会持续加载无法完成,也无错误返回。
更新:排查后定位到问题出在fopen函数。
ini_set('display_startup_errors', 1); ini_set('display_errors', 1); error_reporting(-1); $file = "MYTempFiles/myXML.xml"; $returnFile = file_put_contents($file, file_get_contents('https://www.example.com/myXML'), LOCK_EX); $sftpFile = "/username/myXML.xml"; if($returnFile === false) { die('<p class="center">There was an error processing the XML file.</p>'); } else { echo "<p>$returnFile bytes written to file.</p>"; echo "\r <p>request-" . time()."</p>"; } $sftp_server = "sftp.example.com"; $sftp_userpass = "example_pwd"; $sftp_username = "example_username"; $sftp_port ="2245"; class SFTPConnection { private $connection; private $sftp; public function __construct($host, $port) { $this->connection = ssh2_connect($host, $port); if (! $this->connection) throw new Exception("Could not connect to $host on port $port."); } public function login($username, $password) { if (! ssh2_auth_password($this->connection, $username, $password)) throw new Exception("Could not authenticate with username $username " . "and password $password."); $this->sftp = ssh2_sftp($this->connection); if (! $this->sftp) throw new Exception("Could not initialize SFTP subsystem."); } public function uploadFile($local_file, $remote_file) { $sftp = $this->sftp; $sftp = (int)$sftp; $stream = fopen("ssh2.sftp://$sftp$remote_file", 'w'); if (! $stream) throw new Exception("Could not open file: $remote_file"); $data_to_send = file_get_contents($local_file); if ($data_to_send === false) throw new Exception("Could not open local file: $local_file."); if (fwrite($stream, $data_to_send) === false) throw new Exception("Could not send data from file: $local_file."); fclose($stream); } } try { $mySftp = new SFTPConnection($sftp_server, $sftp_port); $mySftp->login($sftp_username, $sftp_userpass); $mySftp->uploadFile($file, $sftpFile); } catch (Exception $e) { echo $e->getMessage() . "\n"; }
开启错误调试并移除@抑制符后,得到如下警告:
Warning: fopen(): Unable to open ssh2.sftp://6/username/myXML.xml on remote host in /filepath_goes_here/sftp-xml-file.php on line 51 Warning: fopen(ssh2.sftp://6/username/myXML.xml): Failed to open stream: operation failed in /filepath_goes_here/sftp-xml-file.php on line 51 Could not open file: /username/myXML.xml
已做排查:
- 对比两个PHP版本的phpinfo信息,未发现明显差异
- 确认SFTP连接正常
- 将PHP7.4的SSH2升级到v1.3.1后仍能正常运行,但PHP8.1环境下依旧报错
- 确认PHP8.1的
allow_url_fopen设置为on
内容的提问来源于stack exchange,提问作者gprobst
相关产品推荐
相关产品推荐

