dougou6727 2015-03-27 18:47
浏览 100

使用PHP ftp_get()检索带有通配符文件名的文件

I have a file on an FTP with a dynamic filename. The schema looks something like:

ABCD_2_EFGH_YYMMDD_YYMMDD_randomnumber_.TXT

The dates (YYMMDD) reflect the previous day and current day and the randomnumber value is a count of the records in the file and varies each day.

I am attempting to retrieve the file using PHP but I am having trouble using a wildcard name. Here is a sample of the code:

<?php
$yesterday = strtotime('-1 day', time());
$today = strtotime('-0 day', time());
$local_file = "ABCD_2_EFGH__".date('Y-m-j', $yesterday).".txt";
$server_file = "ABCD_2_EFGH_".date('ymd', $yesterday)."_".date('ymd', $today)."_*.txt";

$conn_id = ftp_connect(ftpaddress);
$login_result = ftp_login($conn_id, 'username', 'password');
ftp_chdir($conn_id, 'subdirectory name');
ftp_get($conn_id, $local_file, $server_file, FTP_BINARY);
?>

When running this code i get the following error:

ftp_get() expects parameter 3 to be a valid path

I have also tried using glob() for $server_file and receive the same error.

Does anyone know how to use dynamic filenames with ftp_get()?

  • 写回答

2条回答 默认 最新

  • doucheng2053 2015-03-30 06:43
    关注

    The ftp_get can be used to download a single file only. No wildcards are supported.


    The only reliable way is to list all files, filter them locally and then download them one-by-one:

    $conn_id = ftp_connect("ftp.example.com") or die("Cannot connect");
    ftp_login($conn_id, "username", "password") or die("Cannot login");
    ftp_pasv($conn_id, true) or die("Cannot change to passive mode");
    
    $files = ftp_nlist($conn_id, "/path");
    
    foreach ($files as $file)
    {
        if (preg_match("/\.txt$/i", $file))
        {
            echo "Found $file
    ";
            // download with ftp_get
        }
    }
    

    Some (most) servers will allow you to use a wildcard directly:

    $conn_id = ftp_connect("ftp.example.com") or die("Cannot connect");
    ftp_login($conn_id, "username", "password") or die("Cannot login");
    ftp_pasv($conn_id, true) or die("Cannot change to passive mode");
    
    $files = ftp_nlist($conn_id, "/path/*.txt");
    
    foreach ($files as $file)
    {
        echo "Found $file
    ";
        // download with ftp_get
    }
    

    But that's a nonstandard feature (while widely supported).

    For details see my answer to FTP directory partial listing with wildcards.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看