How do I determine whether a given string is a valid Windows filename? I’m thinking of some function that I can give a string and that returns a boolean. It should check for disallowed characters (<>:”/\|?*) and for reserved words (CON, PRN, et cetera).
isValidWindowsFilename('readme.txt'); // true
isValidWindowsFilename('foo/bar'); // false
isValidWindowsFilename('CON'); // false
I’ve found a MSDN reference describing exactly what is valid: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
I’ve also found the same question for Java, with an answer that does what I need, except that it’s Java and not PHP: Validate a file name on Windows
Here’s the answer on the Java question, ported to PHP.
Note that this function does not impose any limit on the length of the filename, but a real filename may be limited to 260 or 32767 chars depending on the platform.
Here’s some test code to verify its correctness.