简体   繁体   English

如何在PHP中使用ftp_get下载多个文件

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

I have this code that will run everyday at 12am. 我有这个代码,每天早上12点运行。 It currently can only be used to grab the latest file in the server using ftp_mdtm (modified time). 它目前只能用于使用ftp_mdtm (修改时间)获取服务器中的最新文件。 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 . 我目前正在使用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);

?>

You could use the date function and compare that to $time 您可以使用date函数并将其与$time进行比较

If you create an array, named something like $todaysModifiedFiles , and then you could push the $mostRecent object on to it if it's been modified since 12:00AM when you check its modified time by comparing it to time now. 如果你创建了一个类似于$todaysModifiedFiles的数组,那么你可以将$mostRecent对象推送到它,如果它从上午12:00开始被修改,当你通过比较现在的时间来检查它的修改时间时。

Then loop through the array for each of your following processes in the script. 然后在脚本中为每个后续进程循环遍历数组。

$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 will have all the files less than 24hours old, loop that to download, or just add the download inside the if() clause $results将包含所有小于24小时的文件,循环下载,或者只是在if()子句中添加下载

Well i manage to solve it with some adjustment from @Dagon code 我设法通过@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;

} }

then Loop the array to get multiple data for that day using ftp_get 然后使用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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM