<?php
/**
* ftp上传
*/
namespace App\Linlib;
use Illuminate\Support\Facades\Config;
/**
* Class FtpUpload
* @package App\Linlib
*/
class FtpUpload
{
/**
* @var string
*/
private $disk_name;
/**
* FtpUpload constructor.
* @param $host
* @param $port
* @param $username
* @param $password
*/
public function __construct($host, $port, $username, $password)
{
$config = [
'driver' => 'ftp',
'host' => $host,
'port' => $port,
'username' => $username,
'password' => $password,
];
$this->disk_name = "disk" . rand(1000, 9999);
Config::set('filesystems.disks.' . $this->disk_name, $config);
}
/**
* @param $basePath
* @param $folder
* @param $files
*/
private function getFolderFiles($basePath, $folder, &$files)
{
$dir = dir($folder);
while (false !== $entry = $dir->read()) {
if ('.' == $entry || '..' == $entry) {
continue;
}
$new = "$folder/$entry";
if (is_dir($new)) {
$this->getFolderFiles($basePath, $new, $files);
} else {
$files[$new] = str_replace($basePath, "", $new);
}
}
}
/**
* @param $files
* @param $remoteBasePath
* @return bool
*/
private function multiUploadFile($files, $remoteBasePath)
{
set_time_limit(0);
foreach ($files as $key => $value) {
$path = pathinfo($value);
$remotePath = $remoteBasePath . str_replace("\\", "/", $path["dirname"]);
\Storage::disk($this->disk_name)->putFileAs($remotePath, $key, $path["basename"]);
}
return true;
}
/**
* @param $folder
* @param $remotePath
*/
public function uploadFolder($folder, $remotePath = "/")
{
$files = [];
$this->getFolderFiles($folder, $folder, $files);
$this->multiUploadFile($files, $remotePath);
}
}