Page 1 of 1

Copying contents of a folder

Posted: Wed May 18, 2016 9:41 am
by sobha
This function only copies files in a folder from remote to source.But I need to modify this function to copy all the folders and its contents..Eg: FolderA contains Folder1,Folder2,Folder3, and Folder 1 contains file1,file2 and file3.Please help

Code: Select all

public function CopyFile($remote_file, $local_file)
	{
		$sftp = $this->sftp;
		$stream = @fopen("ssh2.sftp://$sftp$remote_file", 'r');
		if (! $stream)
			throw new \Exception("Could not open file: $remote_file");
		//$contents = stream_get_contents($stream);
		$contents=@file_get_contents($remote_file);
		@fclose($stream);

		$stream = @fopen("ssh2.sftp://$sftp$local_file", 'w');
		if (! $stream)
			throw new \Exception("Could not open file: $local_file");
		if (@fwrite($stream, $contents) === false)
			throw new \Exception("Could not send data from file: $local_file.");
		//file_put_contents ($local_file, $contents);
		@fclose($stream);
		$this->deleteFile($remote_file);
	}

Re: Copying contents of a folder

Posted: Wed May 18, 2016 3:00 pm
by Christopher
I don't think sftp supports recursive copying. Use rsync, mget or scp -r.

You could fetch the directory and loop manually, but that would probably be a lot of work.

Re: Copying contents of a folder

Posted: Tue May 24, 2016 5:05 pm
by thinsoldier
If you control the destination server as well you could maybe zip up the entire folder structure, ftp the zip, and then extract the entire folder structure on the destination server.

Re: Copying contents of a folder

Posted: Tue May 24, 2016 6:23 pm
by Christopher
That could be done as a web service. Send a HTTP request for a path and have the target server zip up the directory and return it as the response.

Re: Copying contents of a folder

Posted: Tue May 24, 2016 10:25 pm
by thinsoldier
Also I think there is some bash terminal command that will print out the path of every folder & file starting with the deepest nesting and moving up to the present working directory root. You could turn the output from that into an array and loop over it to guide the ftp uploads.

Re: Copying contents of a folder

Posted: Wed May 25, 2016 2:33 pm
by Christopher
find /path/to/files -depth -type d