>  기사  >  백엔드 개발  >  PHP에서 SFTP 업로드를 구현하는 방법

PHP에서 SFTP 업로드를 구현하는 방법

藏色散人
藏色散人원래의
2021-09-14 10:57:302668검색

PHP에서 SFTP 업로드를 구현하는 방법: 1. "class SFTPConnection private $connection...try{...}catch{...}" 코드를 생성합니다. 2. "sftp -oPort=port user@"를 실행합니다. 서버" 진술 그게 전부입니다.

PHP에서 SFTP 업로드를 구현하는 방법

이 기사의 운영 환경: Windows 7 시스템, PHP 버전 7.1, DELL G3 컴퓨터

PHP로 sftp 업로드를 구현하는 방법은 무엇입니까?

php는 SFTP 파일 업로드를 구현합니다

php는 php.net 공식 웹사이트에 있는 방법을 사용하여 sftp 파일 업로드를 구현합니다. 코드는 다음과 같습니다.

class SFTPConnection
{
    private $connection;
    private $sftp;

    public function __construct($host, $port=22)
    {
        $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;
        $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
{
    $sftp = new SFTPConnection("localhost", 22);
    $sftp->login("username", "password");
    $sftp->uploadFile("/tmp/to_be_sent", "/tmp/to_be_received");
}
catch (Exception $e)
{
    echo $e->getMessage() . "\n";
}

그런데 이 과정에서 문제가 발생했습니다. PHP 5.6 .31 (cli) (build: Aug 2 2017 15:05:23) ,

$stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');

fopen 실행 시 실행 파일에서 "Segmentation failure" 오류가 보고되며, 다음 방법을 사용하여 이를 해결할 수 있습니다.

$stream = @fopen("ssh2.sftp://" . intval($sftp) . $remote_file, 'w');

그 중 sftp 업로드를 구현할 때 업로드된 파일과 업로드 디렉터리의 차이점(예: /upload 및 /upload/test.txt 문제)에 주의를 기울이지 않아 fopen(): Unable이 발생했습니다. 원격 호스트에서 php: //5/upload를 실행할 때마다 보고되는 ssh2.sftp를 열려면 문제에 대한 해결책은 Serious, 대문자로 시작됨 심각한

위는 PHP로 수행됩니다. SFTP 서버에 로그인하기만 하면 됩니다. 확인하면 결과를 알 수 있습니다.

sftp 명령 로그인 방법:

sftp -oPort =port user@server 그런 다음 비밀번호를 입력한 후 상대 디렉터리로 이동하여 파일이 있는지 확인할 수 있습니다.

추천 학습: "PHP 비디오 튜토리얼"

위 내용은 PHP에서 SFTP 업로드를 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.