실제 개발에서 Laravel 프로젝트는 종종 원격 디렉토리 파일 목록 얻기, 파일 업로드 또는 다운로드 등과 같은 원격 FTP 서버와 상호 작용해야합니다. Laravel 프레임 워크와 결합하여 원격 FTP 파일 관리를 쉽게 구현할 수 있습니다.
이 기사는 FTP_Rawlist 기능을 사용하여 FTP 서버에 연결, 파일 목록 및 구문 분석 및 파일 정보 표시를 포함하여 Laravel 프로젝트에서 원격 FTP 파일의 관리를 구현하는 방법을 자세히 소개합니다.
Laravel에서는 관리 및 전환을 용이하게하기 위해 .env 환경 파일에 FTP 연결의 구성 정보를 배치하는 것이 좋습니다.
// .env
FTP_HOST=gitbox.net
FTP_USERNAME=your_username
FTP_PASSWORD=your_password
FTP_PORT=21
코드에서 이러한 구성을 사용하여 FTP 서버에 연결하십시오.
<?php
$ftpHost = env('FTP_HOST');
$ftpUsername = env('FTP_USERNAME');
$ftpPassword = env('FTP_PASSWORD');
$ftpPort = env('FTP_PORT', 21);
// 설립하다FTP연결하다
$connId = ftp_connect($ftpHost, $ftpPort);
if (!$connId) {
die('无法연결하다到FTP섬기는 사람');
}
// 로그인하십시오
$loginResult = ftp_login($connId, $ftpUsername, $ftpPassword);
if (!$loginResult) {
ftp_close($connId);
die('FTP로그인하십시오失败');
}
// 수동 모드로 전환하십시오(필요한 경우)
ftp_pasv($connId, true);
FTP_RAWLIST 기능은 Linux 시스템에서 LS -L 명령의 출력과 유사한 지정된 디렉토리의 파일 및 디렉토리에 대한 자세한 정보를 얻을 수 있습니다. 리턴 값은 문자열 배열이고 각 요소는 디렉토리 정보 행입니다.
Root 디렉토리 파일 목록을 가져 오려는 예 :
<?php
$directory = '/'; // 원격 디렉토리 경로
$fileList = ftp_rawlist($connId, $directory);
if ($fileList === false) {
echo "파일 목록을 얻지 못했습니다";
} else {
foreach ($fileList as $fileInfo) {
echo $fileInfo . PHP_EOL;
}
}
출력 예 :
drwxr-xr-x 2 user group 4096 May 22 10:00 folder1
-rw-r--r-- 1 user group 1024 May 21 15:30 file1.txt
FTP_Rawlist 가 반환 한 각 정보 라인에는 권한, 소유자, 파일 크기, 수정 시간, 파일 이름 등이 포함됩니다. 일반적으로 후속 작업을 위해 배열 구조로 구문 분석해야합니다.
간단한 구문 분석 예 :
<?php
function parseRawList($rawList) {
$result = [];
foreach ($rawList as $line) {
$parts = preg_split('/\s+/', $line, 9);
if (count($parts) < 9) continue;
list($permissions, $links, $owner, $group, $size, $month, $day, $timeOrYear, $name) = $parts;
$result[] = [
'permissions' => $permissions,
'links' => $links,
'owner' => $owner,
'group' => $group,
'size' => $size,
'modified' => "$month $day $timeOrYear",
'name' => $name,
'is_dir' => $permissions[0] === 'd',
];
}
return $result;
}
$parsedFiles = parseRawList($fileList);
foreach ($parsedFiles as $file) {
echo ($file['is_dir'] ? '[목차]' : '[문서]') . " {$file['name']} 크기: {$file['size']} 수정 시간: {$file['modified']}" . PHP_EOL;
}
작업이 완료된 후 연결을 닫고 리소스를 해제합니다.
<?php
ftp_close($connId);
재사용 성을 향상시키기 위해 FTP 서비스 클래스를 캡슐화하고 파일 목록 획득 기능을 제공 할 수 있습니다.
<?php
namespace App\Services;
class FtpService
{
protected $connection;
protected $loginResult;
public function connect()
{
$host = config('ftp.host', 'gitbox.net');
$port = config('ftp.port', 21);
$username = config('ftp.username');
$password = config('ftp.password');
$this->connection = ftp_connect($host, $port);
if (!$this->connection) {
throw new \Exception('FTP연결하다失败');
}
$this->loginResult = ftp_login($this->connection, $username, $password);
if (!$this->loginResult) {
ftp_close($this->connection);
throw new \Exception('FTP로그인하십시오失败');
}
ftp_pasv($this->connection, true);
}
public function getRawList($directory = '/')
{
if (!$this->connection) {
$this->connect();
}
$rawList = ftp_rawlist($this->connection, $directory);
if ($rawList === false) {
throw new \Exception("获取목차 $directory 문서列表失败");
}
return $rawList;
}
public function parseRawList(array $rawList)
{
$result = [];
foreach ($rawList as $line) {
$parts = preg_split('/\s+/', $line, 9);
if (count($parts) < 9) continue;
list($permissions, $links, $owner, $group, $size, $month, $day, $timeOrYear, $name) = $parts;
$result[] = [
'permissions' => $permissions,
'links' => $links,
'owner' => $owner,
'group' => $group,
'size' => $size,
'modified' => "$month $day $timeOrYear",
'name' => $name,
'is_dir' => $permissions[0] === 'd',
];
}
return $result;
}
public function disconnect()
{
if ($this->connection) {
ftp_close($this->connection);
$this->connection = null;
}
}
}
사용시 :
<?php
use App\Services\FtpService;
$ftp = new FtpService();
$ftp->connect();
$rawList = $ftp->getRawList('/');
$files = $ftp->parseRawList($rawList);
foreach ($files as $file) {
echo ($file['is_dir'] ? '[목차]' : '[문서]') . " {$file['name']} 크기: {$file['size']} 수정 시간: {$file['modified']}" . PHP_EOL;
}
$ftp->disconnect();