php ftp check if folder exists always return error

2019-04-11 02:09发布

问题:

can someone please tell me what I'm doing wrong in this code?

if($id != '') {
    if(is_dir("../public_html".$tem_pasta['path']."/pics/".$id)) {
        echo "pasta já existia";
        $destination_file = "../public_html".$tem_pasta['path']."/pics/".$id."/".$myFileName;
    } else {
        //pasta nao existia
        if (ftp_mkdir($conn_id, "../public_html".$tem_pasta['path']."/pics/".$id)) {
            $destination_file = "../public_html".$tem_pasta['path']."/pics/".$id."/".$myFileName;
        //echo "pasta criada<br>";
        } else {
            echo "erro, não criou a pasta<br>";
        }
    }
} else {
    $destination_file = "../public_html".$tem_pasta['path']."/pics/".$myFileName;
}

it checks if I've a folder ($id) within my pics directory, and if not the script creates a new one. works good, but if I try to upload another file to the previous created folder it does return an error, saying it didn't create the folder...

thanks

回答1:

is_dir works only on the local file-system. If you want to check if a ftp-directory already exists try this:

function ftp_is_dir($ftp, $dir)
{
    $pushd = ftp_pwd($ftp);

    if ($pushd !== false && @ftp_chdir($ftp, $dir))
    {
        ftp_chdir($ftp, $pushd);   
        return true;
    }

    return false;
} 

if($id != '') {
    if(ftp_is_dir($conn_id, "../public_html".$tem_pasta['path']."/pics/".$id)) {
    // and so on...


回答2:

I don't think you can use is_dir on a FTP resource, what you should do is check if the size of the dir/file is -1 with ftp_size.

Because I think what now happens is: you are trying to make the same folder again, and this is why a error occurs.

Edit: Or check with ftp_chdir!

<?php 
function ftp_directory_exists($ftp, $dir) 
{ 
    // Get the current working directory 
    $origin = ftp_pwd($ftp); 

    // Attempt to change directory, suppress errors 
    if (@ftp_chdir($ftp, $dir)) 
    { 
        // If the directory exists, set back to origin 
        ftp_chdir($ftp, $origin);    
        return true; 
    } 

    // Directory does not exist 
    return false; 
} 
?> 

Should work!



回答3:

Use ftp_nlist and in_array

$ftp_files = @ftp_nlist($this->connection, $directory);

if ($ftp_files === false) {
    throw new Exception('Unable to list files. Check directory exists: ' . $directory);
}

if (!in_array($directory, $ftp_files)) {
    $ftp_mkdir = @ftp_mkdir($this->connection, $directory);

    if ($ftp_mkdir === false) {
        throw new Exception('Unable to create directory: ' . $directory);
    }
}


标签: php ftp