PHP FTP 文件管理

FTP 协议路径访问范文

$strFtpUrl = 'ftp://www:[email protected]:5566';

# 检测一个文件是否存在

$strFileName = strFtpUrl.'/www/45626.mp4';

if (file_exists($strFtpUrl))
{
    echo "The file $filename exists";
}
else
{
    echo "The file $strFtpUrl does not exist";
}

# 上传一个文件

$resLocalFile = fopen('jzztd.mp4', 'r');

$strDesFile = strFtpUrl.'/7788.mp4';

# 使用 file_put_contents 传输文件
if(file_put_contents($strDesFile, $resLocalFile))
{
    echo 'ftp upload successful';
}
else
{
    echo 'ftp upload failed';
}

# 使用  stream_copy_to_stream 传输文件

$resDesFile = fopen(strDesFile, 'w');

if(stream_copy_to_stream($resLocalFile, $resDesFile))
{
    echo 'ftp upload successful';
}
else
{
    echo 'ftp upload failed';
}

# 删除一个文件
$strDesFile = strFtpUrl.'/7788.mp4';
unlink($strDesFile);

FTP 连接资源访问

#remotefile
$strRemoteFile = 'files.zip';

# local file
$strLocalFile = 'files.zip';

# 创建ftp连接资源
$resConnect = ftp_connect( 192.168.33.188,5566 );

# 登录账户
$boolLoginResult = ftp_login( $resConnect, 'www', 'password' );

# 下载一个文件
if ( ftp_get( $resConnect, $strLocalFile, $strRemoteFile, FTP_BINARY ) )
{
    echo "WOOT! Successfully written to $strLocalFile \n";
}
else
{
    echo "Doh! There was a problem\n";
}

# 上传一个文件
if ( ftp_put( $resConnect, $strRemoteFile, $strLocalFile, FTP_BINARY ) )
{
    echo "WOOT! Successfully written to $strLocalFile \n";
}
else
{
    echo "Doh! There was a problem\n";
}

# 删除一个文件
if (ftp_delete($resConnect, $strRemoteFile)) {
 echo "$strRemoteFile deleted successful\n";
} else {
 echo "could not delete $strRemoteFile\n";
}

# 递归创建目录  默认函数不支持递归创建目录
function mkdir($resConnect,$strDir)
{
    $arrDir = explode("/", $strDir);

    $strPath = "";

    $boolResult = true;

    for ($i=0;$i<count($arrDir);$i++)
    {
        $strPath.="/".$arrDir[$i];

        if(!@ftp_chdir($resConnect,$strPath))
        {
            @ftp_chdir($resConnect,"/");

            if(!@ftp_mkdir($resConnect,$strPath))
            {
                $boolResult=false;
                break;
            }
        }
    }
    return $boolResult;
}

# 检测 ftp 连接状态 默认函数不支持检测状态
function checkStatus($resConnect)
{
    return ftp_pasv($resConnect, true);
}

# 执行一条ftp命令
$strCommand = 'ls -al';
if(ftp_exec($resConnect, $strCommand))
{
    echo "$strCommand executed successfully <br />\n";
}
else
{
    echo 'could not execute ' . $strCommand;
}

# 关闭
ftp_close( $resConnect );