简体   繁体   中英

FTP muliple files upload PHP

I'm trying to upload files to FTP from PHP. It actually works, but not with multiple files. This is the code I have;

        for($i = 0; $i < count($data['data']['metas']); $i++)
    {
        echo "<li>".$data['data']['metas'][$i]["name"]."</li>";
        echo "<li>".$data['data']['metas'][$i]["file"]."</li>";
        echo "<li>".$data['data']['metas'][$i]["size2"]."</li>";
    }

This actually works. It will return the data for the files I uploaded, like this;

- FILENAME01.EXT
- upload/FILENAME01.EXT
- 198.96 KB
- FILENAME02.EXT
- upload/FILENAME01.EXT
- 93.77 KB
- FILENAME03.EXT
- upload/FILENAME03.EXT
- 94.59 KB

So far, so good. Now I'm adding the upload to FTP code, and this is what I have (directly under the code above);

    for($i = 0; $i < count($data['data']['metas']); $i++)
    {
    $host = "ftp.domain.com";
    $username = "myuser";
    $password = "mupass";
    $local_file = $data['data']['metas'][$i]["file"];
    $remote_file = $data['data']['metas'][$i]["name"];

    $con = ftp_connect($host, 21) or die("Cant connect");
    $log = ftp_login($con, $username, $password) or die("Wrong credentials");

    ftp_pasv($con, true);

    $upload = ftp_put($con, $remote_file, $local_file, FTP_BINARY);
    if($upload) echo 'ftp error';
    ftp_close($con);

    echo 'ftp success';
    exit;
    }

This will return "ftp errorftp success" on one line under the information about the files I uploaded. Only the first file that I uploaded will be uploaded to FTP, not all of them. I can't seem to figure out why. What am I missing here? Appreciate any help.

The reason you are getting echo of ftp error is the $upload variable will have a true value when first file is uploaded. and then you have exit at the end of the code that will stop the script to continue loop. Please remove the exit; and try. also see this reference. Here
Also please do not open and close the ftp connection within loop, make it close when the loop will complete and it uploads all the files to ftp.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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