System cannot find the path specified rename file

1.6k views Asked by At

I am trying to rename a file but I get this error.

$newFile = "$surname _$firstname _$dob";
$string = str_replace(' ', '', $newFile);
rename($filename, "$string.pdf");

This code produces this error

Warning: rename(0001_D_A.pdf,Mccoy_Edward_11/22/2016.pdf): The system cannot find the path specified. (code: 3) in C:\xampp\htdocs\script.php on line 7

However if I change the code to use a normal string without a variable it will rename the file without any error.

$newFile = "$surname _$firstname _$dob";
$string = str_replace(' ', '', $newFile);
rename($filename, "helloworld");

The output from $string is -

Mccoy_Edward_11/22/2016
2

There are 2 answers

0
Musa On

The / in the date are invalid for file names and are interpreted as directory separators by the function.
Use - instead to separate the date parts i.e. mm-dd-yyyy

$newFile = "{$surname}_{$firstname}_{$dob}";
$string = str_replace('/', '-', $newFile);
rename($filename, "$string.pdf");
2
dev0 On

That's because the slashes are invalid characters in a windows file name (they act as directory separators on unix-like systems). You have to replace them with something valid, e.g. underscores: $string = str_replace('/', '_', $newFile);