Search code examples
phpftpaccess-rights

File duplicates at upload with ftp_put() in php


So the situation is that lets say "client" changed their ftp server and I have a script that uploads stuff on their server via ftp_put(). I think they have different permissions now on their ftp server when I upload the files. Uploading behaves really weirdly with their new server, it duplicates some files about 5 times, others it doesn't duplicate at all. Keep in mind the same script worked correctly on their old server.

I noticed from the screenshot they sent me, that there's only read and write permissions on their server now. It used to have delete permission also. When I tried to upload files to our own server, and took away deleting permissions, everything stopped working.

So my thought is that, this is the issue maybe since logs showed, I might be totally wrong here, ftp_put() tries to delete files before it uploads them to a server to avoid duplicates. Is that correct and is there workaround to that?

The function itself what sends the files is really easy:

function send_to_ftp($ftp_server, $ftp_username, $ftp_password, $fileName, 

    $subFolder = "n/") {

        $ftp_conn = ftp_connect($ftp_server);
        if (!$ftp_conn) return false;
        $login = ftp_login($ftp_conn, $ftp_username, $ftp_password);
        $reciver_path = $subFolder . end(explode('/', $fileName));
        $local_folder = $fileName;
        return (ftp_put($ftp_conn, $reciver_path, $local_folder, FTP_ASCII));
        //ftp_close($ftp_conn);
    }

Solution

  • It is missing in the documentation on php.net but is mentioned in a comment. ftp_put tries to overwrite the existing file, and this is why you have issues with the permissions. The doubleing might be, without reading the source code of the php ftp_put function, that the overwrite really is a delete and upload, or that you are running the function multiple times.

    I recommend checking if the file already exists before trying to upload it (regardless, checking files are less costly in network traffic then uploading a full sized file).

    Use ftp_nlist to get the content in the target path and see if it exists. http://php.net/manual/en/function.ftp-nlist.php

    If you need to upload already existing file you need to look over your permissions with the owner of the server.