skip to Main Content

I use the ftp_nlist command to check if the folder doesn’t exist, then create it with the ftp_mkdir command.

But the problem that is there and has recently been created for me is that sometimes ftp_nlist returns a false value, which causes the ftp_mkdir command to encounter an error.

And what is more surprising is that in the next attempt, sometimes the ftp_nlist command that I try returns the existing array, which is correct and expected.

This problem happened to me recently and it was not a problem before.

Please guide me if anyone knows. thanks

if(!ftp_nlist($ftp_conn , 'public_html/images')) {
    ftp_mkdir($ftp_conn, 'public_html/images');
}

2

Answers


  1. Chosen as BEST ANSWER

    When I use ftp_chdir($ftp_conn, $directory), if the folder exists, it returns true, but if the folder does not exist, it does not return false and gives an error.

    KIKO Software


  2. The problem here is that ftp_nlist() can return false due to many reasons, not only because the directory doesn’t exist.

    I think it would be better to use ftp_chdir(). If it is successful you know the directory exist and you can use it. If it fails you can make the directory with ftp_mkdir() and retry the ftp_chdir() again until you succeed.

    It might be wise to exit this loop after a number of tries and report an error.

    In code that could look something like this:

    $counter = 0;
    while (!ftp_chdir($ftp_conn, 'public_html/images')) {
        $counter++;
        if ($counter > 3) {
            break; // we failed, perhaps we should do more than just "break"?
        }
        ftp_mkdir($ftp_conn, 'public_html/images');
    }
    

    You could create your own function for this:

    function gotoFtpDir(string $directory): bool
    {
        $counter = 0;
        while (!ftp_chdir($ftp_conn, $directory)) {
            $counter++;
            if ($counter > 3) {
                return false;
            }
            ftp_mkdir($ftp_conn, $directory);
        }
        return true;
    }
    

    This function will go to the given directory, create it when it doesn’t exist, and it will return true on success and false on failure.

    I do think that the standard PHP FTP client is limited in its capabilities. There are lots of PHP FTP client libraries on the internet, there might be a better one out there.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search