PHP file_exists but rename fails "No such file or directory ..."?

The thinking about creating the file in question is a little behind the offending function, I tried running a while loop to buy some time before triggering the rename.

$no_file = 1;   
while($no_file && $no_file < 300)
{   // generation of Worksheet.xls may lag behind function -- WAIT FOR IT
    if(file_exists($old_path))
    {   $no_file = 0;
        rename($old_path, $new_path);
    }   else $no_file++;
}
if($no_file) die("Error: Worksheet.xls not found");

      

In this configuration, I think rename () can only be called if file_exists () returns true, but for the life of me I can't figure out how / why then rename () is called and then not returned ...

PHP Warning: Rename (C: \ WAMP \ WWW \ Demox / WP-Content / Plugins / Cats Man / Shop-Manager / Resume / Worksheets / Worksheet.xls, C: \ WAMP \ WWW \ Demox / WP-Content / Plugins / cat- man / shop-manager / resume / expression / TESTING / 2012 / Worksheet.xls) No such file or directory ...

+3


source to share


3 answers


You are probably saying that it statements/TESTING/2012/

doesn't exist. Create these directories with mkdir()

so it can save the file.



mkdir( 'C:\wamp\www\demox/wp-content/plugins/cat-man/store-manager/summary/statements/TESTING/2012/', 777, true);

      

+10


source


Removed, however, this code opens up the possibility of a race condition where your file can change between checking for its existence and trying to rename it. Better to try to rename directly from the block try/catch

and address the error directly.

You must explicitly break out of the loop with a break

post-rename statement . And the setup $no_file = 0;

before the rename prematurely celebrates the victory.



Also, if you are looping with the purpose of delaying, you need to do execution, otherwise the loop will complete as quickly as PHP can handle it. Take a look at time_nanosleep

. If you end the loop while

, you will see that it ends very quickly:

$time_start = microtime(true);
$x = 0;
while ($x < 300) {
    file_exists("index.php");
    $x++;
}
echo sprintf("300 loops in %.9f seconds", microtime(true) - $time_start);

// 300 loops in 0.000626087 seconds

      

+1


source


Ok, mkdir () solved the problem! Here's the solution in context.

$old_path = $smry_dir."worksheets/Worksheet.xls";
if(@$store_options->paypal_live ==='false')
{   $new_path = $smry_dir."statements/TESTING/$reporting_year";
}   else $new_path = $smry_dir."statements/$reporting_year";
if(!is_dir($new_path)) mkdir($new_path, 777, true);
rename($old_path, $new_path."/Worksheet.xls");

      

Thanks again for your help! DIR statements always exist and I found that while rename () would write a single new $ report_year subdirectory without complaint, it cannot / cannot write recursive "TESTING / $ reporting_year" subroutines.

mkdir recursive parameter to the rescue!

+1


source







All Articles