PHP SFTPファイルアップロードを行う方法

環境
PHP 8.1.2
Ubuntu 22.04.1 LTS

書式
ssh2.sftp://ユーザー名:パスワード@ホスト名:22/path/to/filename
SFTPのファイルアップロードを行います。

形式

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
ssh2.shell://user:pass@example.com:22/xterm
ssh2.exec://user:pass@example.com:22/usr/local/bin/somecmd
ssh2.tunnel://user:pass@example.com:22/192.168.0.1:14
ssh2.sftp://user:pass@example.com:22/path/to/filename
ssh2.shell://user:pass@example.com:22/xterm ssh2.exec://user:pass@example.com:22/usr/local/bin/somecmd ssh2.tunnel://user:pass@example.com:22/192.168.0.1:14 ssh2.sftp://user:pass@example.com:22/path/to/filename
ssh2.shell://user:pass@example.com:22/xterm
ssh2.exec://user:pass@example.com:22/usr/local/bin/somecmd
ssh2.tunnel://user:pass@example.com:22/192.168.0.1:14
ssh2.sftp://user:pass@example.com:22/path/to/filename

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// 変数の宣言
$strHost = '172.17.10.6';
$strPort = 22;
$strUser = 'root';
$strPw = '12345#@!';
$uploadPath = '/www/';
$upFileName = 'test001.pdf';
// 書き込むファイルの取得
$opFile = file_get_contents($uploadPath . $upFileName);
// SFTPでの書き込
$sConnect = $strUser . ':' . $strPw . '@' . $strHost . ':' . $strPort;
$strFile = fopen('ssh2.sftp://' . $sConnect . $uploadPath . $upFileName, 'w');
fwrite($strFile, $opFile);
fclose($strFile);
// 変数の宣言 $strHost = '172.17.10.6'; $strPort = 22; $strUser = 'root'; $strPw = '12345#@!'; $uploadPath = '/www/'; $upFileName = 'test001.pdf'; // 書き込むファイルの取得 $opFile = file_get_contents($uploadPath . $upFileName); // SFTPでの書き込 $sConnect = $strUser . ':' . $strPw . '@' . $strHost . ':' . $strPort; $strFile = fopen('ssh2.sftp://' . $sConnect . $uploadPath . $upFileName, 'w'); fwrite($strFile, $opFile); fclose($strFile);
// 変数の宣言
$strHost = '172.17.10.6';
$strPort = 22;
$strUser = 'root';
$strPw = '12345#@!';
$uploadPath = '/www/';
$upFileName = 'test001.pdf';

// 書き込むファイルの取得
$opFile = file_get_contents($uploadPath . $upFileName); 

// SFTPでの書き込
$sConnect = $strUser . ':' . $strPw . '@' . $strHost . ':' . $strPort;
$strFile = fopen('ssh2.sftp://' . $sConnect . $uploadPath . $upFileName, 'w');
fwrite($strFile, $opFile);
fclose($strFile);

 

PHP

Posted by arkgame