我如何在 PHP 中使用 ftp_get 下载超过 1 个文件

How can i download more than 1 file using ftp_get in PHP

我有这段代码,每天凌晨 12 点 运行。目前只能用于使用ftp_mdtm (modified time). The problem I'm facing is that sometimes the server uploads more than 1 file to the server. How can I download all the latest files for that day? I'm currently using ftp_get.

抓取服务器中的最新文件
<?php

$conn = ftp_connect('abc.com');
ftp_login($conn, 'lalala', '12345');

// get list of files on given path
$files = ftp_nlist($conn, '');

$mostRecent = array(
    'time' => 0,
    'file' => null
);

foreach ($files as $file) {
    // get the last modified time for the file
    $time = ftp_mdtm($conn, $file);

    if ($time > $mostRecent['time']) {
        // this file is the most recent so far
        $mostRecent['time'] = $time;
        $mostRecent['file'] = $file;
    }
}

ftp_get($conn, "$file.zip", $mostRecent['file'], FTP_BINARY);
ftp_close($conn);

$file_open= $file . ".zip";
$path = "./zip/";

$zip = new ZipArchive;
$res = $zip->open($file_open);
if ($res === true) {
  // extract it to the path we determined above
  $zip->extractTo($path);
  $zip->close();
  //echo "$file_open extracted to $path";
} else {
  //echo "I couldn't open $file_open";
}

$servername = "localhost";      //server IP or name
$uname = "lalala";              //username
$pword = "";                    //password
$dbname = "lalala";         //database name

$db = new mysqli($servername, $uname, $pword, $dbname);
// Check connection
if ($db->connect_error) {
     die("Connection failed: " . $db->connect_error);
}

//print_r (glob("test/*.txt"));
//exit();

foreach (glob($path . "/*.TXT") as $file) {
    $file_handle = fopen($file, "r");
    while (!feof($file_handle)) {
        $line = fgets($file_handle);
        $new_file = substr($file, 7);
        //echo $line;

        $query_check = "SELECT filename FROM fos_data WHERE filename = '$new_file'";
        $result=mysqli_query($db,$query_check);
        $row = mysqli_fetch_assoc($result);
        $exist = $row['filename'] . "<br>";
        $rowcount=mysqli_num_rows($result);

        if ($rowcount > 0) {
            $update = " UPDATE  fos_data
                        SET     value       = '$line'
                        WHERE   filename    = '$new_file'";
            $result=mysqli_query($db,$update);
            echo "Data " . $new_file . " Updated <br>";
        }
        else{
            $insert = "INSERT INTO fos_data 
                            (filename,
                                value)
                            VALUES
                            ('$new_file',
                                '$line')";
            $result=mysqli_query($db,$insert);
            echo "Data " . $new_file . " Saved <br>";
        }

        /**/
    }
    fclose($file_handle);

}

mysqli_close($db);

?>

您可以使用 date function 并将其与 $time

进行比较

如果你创建一个数组,命名为 $todaysModifiedFiles,然后你可以将 $mostRecent 对象推到它上面,如果它自 12:00AM 以来被修改,当你检查它的修改将它与现在的时间进行比较。

然后为脚本中的每个后续进程循环数组。

$list = ftp_rawlist($conn, '.');//rawlist gets the dates, nlist does not 

$results = array();
foreach ($list as $line) {//loop the files
    list($perms, $links, $user, $group, $size, $d1, $d2, $d3, $name) =
        preg_split('/\s+/', $line, 9);//rip apart the returned data to get to the date
    $stamp = strtotime(implode(' ', array($d1, $d2, $d3)));
if($stamp < time() + 86400) {//beware of leap secounds
    $results[] = $name);
}

}

$results 将拥有小于 24 小时的所有文件,循环下载,或者只在 if() 子句中添加下载

好吧,我通过@Dagon 代码的一些调整设法解决了这个问题

$contents = ftp_rawlist($conn, '.');
$results = array();
foreach ($contents as $line) {
    list($perms, $links, $user, $group, $size, $d1, $d2, $d3, $name) =
        preg_split('/\s+/', $line, 9);
    $stamp = strtotime(implode(' ', array($d1, $d2, $d3)));
    $datetime = date('d/m/Y', $stamp);
    $results[] = array('name' => $name, 'timestamp' => $stamp, 'date' => $datetime);
}

usort($results, function($a, $b) { return $a['timestamp'] - $b['timestamp']; });
$today_date = date("d/m/Y");

$new_result = search($results, 'date', $today_date);


function search($array, $key, $value){
$results = array();

if (is_array($array)) {
    if (isset($array[$key]) && $array[$key] == $value) {
        $results[] = $array;
    }

    foreach ($array as $subarray) {
        $results = array_merge($results, search($subarray, $key, $value));
    }
}

return $results;

}

然后使用 ftp_get

循环数组以获取当天的多个数据
$array_count = 0;
$temp_array = array();
foreach ($new_result as $new) {
    //todo
    $temp_array["name"] = $new_result["$array_count"]["name"];
    $temp_array["date"] = $new_result["$array_count"]["date"];
    echo "<br>";
    echo "File " . $temp_array["name"];
    echo "<br>";
    echo "Date " . $temp_array["date"];
    echo "<br>";

    // download the latest file using the filename from server
    ftp_get($conn, "$array_count.zip", $temp_array["name"], FTP_BINARY);
    //close connection
    ftp_close($conn);
    }