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

时间:2016-04-27 02:43:20

标签: php zip unzip

我有这个代码每天早上12点运行。它目前只能用于使用ftp_mdtm(修改时间)获取服务器中的最新文件。我面临的问题是服务器有时会向服务器上传多个文件。如何下载当天的所有最新文件?我目前正在使用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);

?>

3 个答案:

答案 0 :(得分:0)

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

进行比较

如果您创建了一个类似于$todaysModifiedFiles的数组,那么您可以将$mostRecent对象推送到它,如果它已经被修改,那么从上午12:00开始,当您检查其修改时时间与现在的时间比较。

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

答案 1 :(得分:0)

$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()子句中添加下载

答案 2 :(得分:0)

我设法通过@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);
    }