`

PHP开发笔记系列(六)- 内置FTP函数

阅读更多

    FTP是我们经常用到的一种服务器,能够用来接收第三方系统发送过来的文件,作为接收点,然后我们的系统再定期访问FTP获取文件,进行内部的业务处理,是一个很方便的中间媒介。


     继《PHP开发笔记系列(五)- INI文件解释 》后,本文《 PHP开发笔记系列(六)- 内置FTP函数 》将讲述如何使用PHP内置的FTP函数进行常用的FTP浏览、上传、下载等操作。

 

     1. 使用PHP内置FTP函数操作ftp

    PHP中内置了FTP函数,可以使用FTP函数进行connect、login、chdir、list等操作,下面我们将通过代码来实验FTP函数的功能。

 

file:ftp-access.php
url:http://localhost:88/ftp/ftp-access.php
<?php
    $host = 'localhost';
    $port = '21';
    $timeout = '30';
    $targetDir = '/';
    
    $username = 'anonymous';
    $password = 'anonymous';
        
    $ftp = ftp_connect($host, $port, $timeout);
    
    if (!$ftp) {
        die('Failed to connect to ftp server['.$host.']!');
    }
    
    $flag = ftp_login($ftp, 'anonymous', 'anonymous');
    if (!$flag) {
        die('Failed to login to ftp server['.$host.']!');
    }
    
    $flag = ftp_chdir($ftp, $targetDir);
    if (!$flag) {
        die('Failed to change directory to ftp server['.$host.']\'s directory['.$targetDir.']!');
    }
    
    echo 'Current directory: '.ftp_pwd($ftp).'<br/>';
    
    $files = ftp_nlist($ftp, $targetDir);
    foreach ($files as $file){
        echo $file.'<br/>';
    }
    
    ftp_quit($ftp); 
    
?>
 

    上面演示了如何使用php的内置函数进行ftp服务器的连接、登陆、切换目录,显示目录中的内容等。


    除了访问ftp服务器外,经常还会用到文件下载与上传,代码如下:


    下载文件:

file:ftp-get.php
url:http://localhost:88/ftp/ftp-get.php
<?php
    ... ...
    
    ftp_get($ftp, "onefile.html", "onefile.html", FTP_BINARY); 
    
    ... ...
?>

 

    上传文件:

 

file:ftp-put.php
url:http://localhost:88/ftp/ftp-put.php
<?php
    ... ...
    
    ftp_put($ftp, "onefile-copy.html", "onefile.html", FTP_BINARY); 
    
    ... ...
?>
 

 

    本文地址:http://ryan-d.iteye.com/admin/blogs//1543414

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics