I’m wring a piece of code in PHP for saving email attachments. Can i assume that this will never fail because different allowed characters between OS?
foreach($message->attachments as $a)
{
// Make dir if not exists
$dir = __DIR__ . "/saved/$uid"; // Message id
if (!file_exists($dir)) mkdir($dir) or die("Cannot create: $dir");
// Save the attachment using original!!! filename as found in email
$fp = fopen($dir . '/' . $a->filename, 'w+');
fwrite($fp, $a->data);
fclose($fp);
}
it is good practice to replace certain characters that may occur in filenames on windows.
Unix can handle almost any character in a file name (but not “/” and 0x00 [the null Character]), but to prevent encoding problems and difficulties on downloading a file I would suggest to replace anything that does not match
/[A-Za-Z0-9_-\.]/g, which satisfies the POSIX fully portable filename format.so a
preg_replace("/[^A-Za-Z0-9_-\.]/g","_",$filename);will do a good job.a more generous approach would be to replace only
|\?*<":>+[]\x00/which leaves special language characters like öäü untouched and is compatible with FAT32, NTFS, any Unix and Mac OS X.in that case use
preg_replace("/[\|\\\?\*<\":>\+\[\]\/]\x00/g","_",$filename);