Search code examples
phpzipunzip

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


I have this code that will run everyday at 12am. It currently can only be used to grab the latest file in the server using 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);

?>

Solution

  • Well i manage to solve it with some adjustment from @Dagon code

    $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

    $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);
        }