Transfer files through SSH SFTP - MiguelFieira/AMO-HANDBOEK GitHub Wiki

Again, i dont have fukking time. Here:

<?php

error_reporting(E_ALL);
ini_set('display_errors', true);

class SFTP
{
    protected $connection;
    protected $sftp;
    protected $config;
    # $host = FTP.pcs.portbase.com

    public function __construct($host, $port) 
    {
        // This makes a connection to the host
        $this->connection = ssh2_connect($host, $port);
        if (! $this->connection)
            throw new Exception("Could not connect to $host on port $port.");
        $this->config = parse_ini_file('/config.ini');
        die($config);
    }

    // Basic login function
    public function login($username, $pass)
    {
        if (! ssh2_auth_password($this->connection, $username, $pass))
            throw new Exception("Could not authenticate with username $username " . "and password $pass.");

        $this->sftp = ssh2_sftp($this->connection);
        if (! $this->sftp)
            throw new Exception("Could not initialize SFTP subsystem.");
    }

    // Scan and show all files in a certain directory, only give along path
    public function scanDir($dir, $remote) {
        $sftp_fd = intval($this->sftp);
        $uri = $dir;
        $paths = [];
        if($remote)
            $uri = "ssh2.sftp://$sftp_fd$dir";
        $connection = $this->connection;


        if($handle = opendir($uri)) {
            if(count(scandir($uri)) > 2) {
                while (false !== ($entry = readdir($handle))) {
                    if ($entry != "." && $entry != "..") {
                        if($remote) {
                            $path = "$uri$entry";
                        } else {
                            $path = "$dir$entry";
                        }
                        $paths[] = $path;
                        echo "<br>$entry";
                    }
                }
            } else {
                throw new Exception("No entries in this dir");
            }
        } else {
            throw new Exception("Dir can't be opened");
        } return $paths;
    }

    // Upload a file to the host
    public function uploadFiles($local_dir)
    {
        $fails = [];
        $sftp_fd = intval($this->sftp);
        $connection = $this->connection;
        $remote_dir = "/home/sftp-test/upload/tmp/";
        $uri = "ssh2.sftp://$sftp_fd$remote_dir";
        $new_uri = str_replace("tmp", "new", $uri);         // uri for /tmp
        $new_path = str_replace("tmp", "new", $remote_dir); // path for /tmp

        if($handle = opendir($local_dir)) {

            // Check if directory is empty
            if(count(scandir($local_dir)) > 2) {
                                                                    echo "Local directory handle: $handle\n<br>";
                                                                    echo "Entries:\n<br>";

                // read out all files in remote directory
                while (false !== ($entry = readdir($handle))) {
                    if ($entry != "." && $entry != "..") {
                        $path = "$local_dir$entry";
                                                                    echo "<br>--------<br>";
                                                                    echo "$entry <br>";
                                                                    echo str_replace(' ', '_',$entry)."<br>";
                                                                    echo "$path <br>";
                        
                        // Check if entry is even a file
                        if (is_file($path)){
                            if($this->getFileSize($path) < (4*1024*1024)) {
                                $remote_file = $remote_dir . $entry;
                                $local_file = $local_dir . $entry;
                                                                    echo "<br> remote location: $remote_file <br>";
                                                                    echo "local location: $local_file <br>";

                                // Upload file
                                if(ssh2_scp_send($connection, $local_file, $remote_file)) {
                                    $new = $new_path . $entry;
                                                                    echo "$new<br>";

                                    // Move file to /new
                                    try { 
                                        ssh2_sftp_rename($this->sftp, $remote_file, $new);
                                                                    echo $remote_file;
                                    }
                                    catch (Exception $e) {
                                        throw $e->getMessage();
                                    }
                                } else {
                                    $fails[] = [$entry,"<br><b>File upload failed<b>"];
                                }
                            } else {
                                $fails[] = [$entry,"<br><b>File is too big (max. 4MB)</b>"];
                            }
                        } else {
                            $fails[] = [$entry, "<br><b>Iteration is not a file</b>"];
                        }
                    }
                } closedir($handle); var_dump($fails);
            } else {
                throw new Exception("No files to upload");
            }
        } else {
            throw new Exception("Directory cannot be opened?");
        }
    }

    /**
     * Download all files from a remote directory to a local one via SSH2
     */
    public function downloadFiles($local_dir)
    {     
        $fails = [];
        $remote_dir = "/home/sftp-test/download/new/";
        $sftp_fd = intval($this->sftp);
        $connection = $this->connection;
        $uri = "ssh2.sftp://$sftp_fd$remote_dir";
        $tmp_uri = str_replace("new", "tmp", $uri);         // uri for /tmp
        $cur_path = str_replace("new", "cur", $remote_dir); // uri for /cur
        $tmp_path = str_replace("new", "tmp", $remote_dir); // path for /tmp

        // open the remote directory
        if ($handle = opendir($uri)) {   

            // Check if directory is empty.
            // The first 2 items in the directory are always a "." and ".."
            if(count(scandir($uri)) > 2) {
                                                                    echo "Remote directory handle: $handle\n<br>";
                                                                    echo "Entries:\n<br><br>";

                // read out all files in remote directory
                while (false !== ($entry = readdir($handle))) {
                    if ($entry != "." && $entry != "..") {
                        $path = $uri . $entry;               // remote file path
                        
                        // check if the file exists
                        if(is_file($path)){
                            $tmp = $tmp_uri . $entry;        // tmp file path to move file to
                            $tmp_file = $tmp_path . $entry;
                                                                    echo "------- <br><br>";
                                                                    echo "entry: $entry\n <br>";
                            
                            // move file to /tmp and list everything down
                            if(rename($path, $tmp)) {
                                $local_file = $local_dir . $entry;
                                $remote_file = $tmp_path . $entry;
                                                                    echo "moved to: " . $tmp . "<br>";
                                                                    echo "local path: " . $local_file . "<br>";
                                                                    echo "remote_file path: " . $remote_file . "<br>";

                                // Download the file
                                if(ssh2_scp_recv($connection, $remote_file, $local_file)){
                                    $cur = $cur_path . $entry;
                                    echo "<br> $cur";

                                    // Move downloaded file to /cur
                                    try {
                                        ssh2_sftp_rename($this->sftp, $tmp_file, $cur);
                                        echo "<br> Files moved to: $cur";

                                    // If file is already in /cur
                                    } catch(Exception $e) {
                                        $fails[] = [$entry, "<br><b>File already exists in CUR</b>"];
                                    }
                                } else {
                                    $fails[] = [$entry, "<br><b>Download failed</b>"];
                                }

                            // If file already exists in TMP
                            } else {
                                $fails[] = [$entry, "<br><b>File already exists in TMP</b>"];
                            }
                        // If file doesn't exist or isn't a normal file
                        } else {
                            $fails[] = [$entry,"<br><b>Iteration is not a file</b>"];
                        }
                    }
                    clearstatcache();
                }
                closedir($handle);
            } else {
                throw new Exception("Download directory is empty");
            }
        }
        /*
        what still needs to happen:
        - Add a correct directory check
        - If files still exist in other folders, perhaps unlink them
        - Full recheck of system code
        */
    }
    
    public function getFileSize($file){
        $sftp = $this->sftp;
        return filesize("ssh2.sftp://$sftp$file");
    }
    
    public function deleteFile($remote_file){
        $sftp = $this->sftp;
        try {
            unlink("ssh2.sftp://$sftp$remote_file");
            echo "file at $remote_file is deleted";
        } catch(Exception $e) {
            echo $e->getMessage() . "/n";
        }
    }
    public function clearDir($dir, $remote) {
        $files = $this->scanDir($dir, $remote);

        foreach($files as $path) {
            echo "$path<br>";
            if(unlink($path)){
                echo "<b>Removed</b> $path<br>";
            }
        }

    }
}



try
{
    $sftp = new SFTP("localhost", 22);
    $sftp->login("sftp-test", "Sam!");
    // $sftp->clearDir("/home/svandergreft/Sites/Test/Verwerken/", false);
    // $sftp->deleteFile("/home/sftp-test/upload/new/test1 copy 4.txt");
    $sftp->scanRemoteDir("/home/sftp-test/upload/tmp/");
    // $sftp->uploadFiles("/home/svandergreft/Sites/Test/PHP/Verwerken/");
    // $sftp->downloadFiles("/home/svandergreft/Sites/Test/PHP/Verwerkt/");
    // $oof = $stfp->getFileSize('test1.txt');
} catch(Exception $e)
{
    echo $e->getMessage() . "\n";
}


/*
What still needs to happen
- Doucle check the code
- Clear up some comments
*/

?>
⚠️ **GitHub.com Fallback** ⚠️