Wednesday 16 December 2009

PHP: How to (Code) to check if a Windows file / folder name is valid.

Two PHP functions to check a string to see if it is a valid windows filename. The first simply checks the string, the second function will replace all occurrences of the invalid characters with a blank.


/**
* Checks to see if a filename is valid for Windows
* Invalid characters are: < > : " / \ | ? *
* Returns false if invalid characters found, else true
*/
function isValidFilename($filename)
{
if(preg_match('/[<>:"\/\\\|?*]/i', $filename))
{
//Invalid characters found
setDebug("Filename '$filename' contained invalid characters.");
return false;
} else {
//No invalid characters, must be valid filename
setDebug("Filename '$filename' contained no invalid characters.");
return true;
}
}

/**
* Removes all invalid characters from a Windows filename.
* Invalid characters are: < > : " / \ | ? *
* Returns the (possibly) modified string
*/
function fixFilename($filename)
{
setDebug("Filename to fix: {$filename}");
$newFilename = preg_replace('/[<>:"\/\\\|?*]/i', "", $filename);
setDebug("Fixed filename: {$newFilename}");
return $newFilename;
}

No comments: