Search code examples
phprename

php rename warning despite being successfull


I am doing a rename so I can move a folder. The move is successful, but I keep getting a warning:

Warning: rename(site_files/259,trash/site_files/259) [function.rename]: No such file or directory in /home/oosman/public_html/lib.php on line 79

This is my code:

$path_parts = pathinfo($file);
$d = $path_parts['dirname'];
$f = $path_parts['basename'];

$trashdir='trash/'.$d;
mkdir2($trashdir);
if(!is_dir($trashdir))
    return FALSE;

rename($file, $trashdir.'/'.$f); // this is line 79 where the warning is coming from

Why am I getting this warning?

FYI the mkdir2 is just my recursive mkdir function

function mkdir2($dir, $mode = 0755)
{
    if (@is_dir($dir) || @mkdir($dir,$mode)) return TRUE;
    if (!mkdir2(dirname($dir),$mode)) return FALSE;
    return @mkdir($dir,$mode);
}

Solution

  • This is just because the source or targeting folder does not exist.

    This will remove the warning anyway but not the best way to solve the question:

    if(file_exists($file) && file_exists($trashdir)){
        rename($file, $trashdir.'/'.$f);
    }
    

    In order to find out what the problem really is, please check following questions:

    1.Does the source file(site_files/259) exist? Does it have an extension like 259.txt?

    From your log , I guess the absolute path of the original file should be /home/oosman/public_html/site_files/259.

    2.Have you successfully created the target folder? Can you see it on the disk and get TRUE from mkdir2()?

    3.I strongly suggest that you use the absolute path but not the relative path when you use rename().

    rename('/home/oosman/public_html/site_files/259', '/home/oosman/public_html/trash/site_files/259');
    

    but not

    rename('site_files/259', 'trash/site_files/259');
    

    Maybe something wrong with the relative path?

    Updated 2014-12-04 12:00:00 (GMT +900):

    Since it is not anything mentioned above could you please log something to help me clarify?

    Please change

    rename($file, $trashdir.'/'.$f);
    

    to

    echo "Before moving:\n"
    echo "Orgin:".file_exists($file)."\n";
    echo "Target parent folder:".file_exists($trashdir)."\n";
    echo "Target file:".file_exists($trashdir.'/'.$f)."\n";
    rename($file, $trashdir.'/'.$f);
    echo "After moving:\n"
    echo "Orgin:".file_exists($file)."\n";
    echo "Target parent folder:".file_exists($trashdir)."\n";
    echo "Target file:".file_exists($trashdir.'/'.$f)."\n";
    

    If this outputs:

    Before moving:
    Origin:1
    Target parent folder:1
    Target file:0
    Warning: rename(site_files/259,trash/site_files/259) [function.rename]: No such file or directory in /home/oosman/public_html/lib.php on line 83
    After moving:
    Origin:0
    Target parent folder:1
    Target file:1
    

    exactly only once, then I am out. If it doesn't, please tell me the difference.