I want to rename files using PHP.
I loop through the directory containing the files and once I find the file, I want to use rename() to do the actual renaming.
So far so simple.
The problem is that the files that need renaming contain illegal characters in the file names. I can strip the illegal character from the name, but when I want to rename the file using the new name, it cannot be found.
So once I get to the point where I can use rename() PHP throws a warning: The system cannot find the file specified. (code: 2).
PHP seems to be unable to recognize the file as a file (is_file() returns false). The file in question is a pdf file, I can open it without any problems in Acrobat Reader. The file was generated on a Mac using Quartz, I am using Windows.
Does anyone have an idea how I can make PHP recognize the file with the illegal character in the name as a file?
PS
This is my code:
$dataDirectory = new RecursiveDirectoryIterator($folders);
foreach ($dataDirectory as $dataName => $dataFileName) {
$isfile = is_file($dataFileName); // false for files with illegal character in filename
$result = rename($dataFileName, 'testname'); // generates warning mentioned above
}
What's the server OS?
If it's Windows, you'll not be able to access files under a UTF-8-encoded filename, because the Windows implementation of the C IO libraries used by PHP will only talk in the system default code page. For Western European installs, that's code page 1252. You can convert a UTF-8 string to cp1252 using iconv:
$winfilename= iconv('utf-8', 'cp1252', $utffilename);
(utf8_decode could also be used, but it would give the wrong results for Windows's extension characters that map to the range 0x80-0x9F in cp1252.)
Files whose names include characters outside the repertoire of the system codepage (eg. Greek on a Western box) cannot be accessed at all by PHP and other programs using the stdio. There are scripting languages that can use native-Unicode filenames through Win32 APIs, but PHP5 isn't one of them.
And of course the step above shouldn't be used when deployed on a different OS where the filesystem is UTF-8-encoded. (ie. modern Linux.)
If you need to seamlessly cross-server-compatible with PHP, you'll have to refrain from using non-ASCII characters in filenames. Sorry.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.