ohayou
ohayou

Reputation: 23

Upload all files from a local folder to SFTP using PHP

Can I upload local directory, to remote directory in SFTP? Or can I upload all files in a directory to SFTP?

I tried to upload all file in a directory this way:

$file = "C:/incoming/360/upload/".date("Ymd")."/*.*";
$dest = "/testing/*.*";

$contents = file_get_contents($file);
file_put_contents("ssh2.sftp://{$sftp}/testing/{$dest}", $contents);

I think that the code above just uploads by filename.

Upvotes: 1

Views: 902

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202197

You have iterate the local files and upload them one-by-one:

$files = glob("C:/incoming/360/upload/".date("Ymd")."/*");

foreach ($files as $file)
{
    $contents = file_get_contents($file);
    $basename = basename($file);
    file_put_contents("ssh2.sftp://{$sftp}/testing/{$dest}", $contents);
}

Though note that using file_get_contents and file_put_contents is pretty ineffective, when dealing with larger files, as you load whole file contents to a memory.

Better use fopen and stream_copy_to_stream.

Upvotes: 1

Related Questions