CodeCharge Studio
search Register Login  

Web Reporting

Visually create Web Reports in PHP, ASP, .NET, Java, Perl and ColdFusion.
CodeCharge.com

YesSoftware Forums -> CodeCharge Studio -> Tips & Solutions

 Sanitize filename

Print topic Send  topic

Author Message
timdw

Posts: 25
Posted: 06/03/2006, 11:03 PM

Little function to sanitize a user supplied file name, and optionally force a file extension:

function sanitize_filename($filename, $forceextension="")
{
/*
1. Remove leading and trailing dots
2. Remove dodgy characters from filename, including spaces and dots except last.
3. Force extension if specified
*/

$defaultfilename = "none";
$dodgychars = "[^0-9a-zA-z()_-]"; // allow only alphanumeric, underscore, parentheses and hyphen

$filename = preg_replace("/^[.]*/","",$filename); // lose any leading dots
$filename = preg_replace("/[.]*$/","",$filename); // lose any trailing dots
$filename = $filename?$filename:$defaultfilename; // if filename is blank, provide default

$lastdotpos=strrpos($filename, "."); // save last dot position
$filename = preg_replace("/$dodgychars/","_",$filename); // replace dodgy characters
$afterdot = "";
if ($lastdotpos !== false) { // Split into name and extension, if any.
$beforedot = substr($filename, 0, $lastdotpos);
if ($lastdotpos < (strlen($filename) - 1))
$afterdot = substr($filename, $lastdotpos + 1);
}
else // no extension
$beforedot = $filename;

if ($forceextension)
$filename = $beforedot . "." . $forceextension;
elseif ($afterdot)
$filename = $beforedot . "." . $afterdot;
else
$filename = $beforedot;

return $filename;
}
echo sanitize_filename("..file<>@**()name.ddd.badextension", "extension")."\n";
echo sanitize_filename("..file<>@**()name.extension.ddd")."\n";
echo sanitize_filename("...", "extension")."\n";
echo sanitize_filename("...")."\n";
echo sanitize_filename("filename")."\n";
echo sanitize_filename("filename", "extension")."\n";
echo sanitize_filename(".xyz...xxx..", "extension")."\n";
echo sanitize_filename(".xyz...xxx..", "")."\n";

produces

file_____()name_ddd.extension
file_____()name_extension.ddd
none.extension
none
filename
filename.extension
xyz__.extension
xyz__.xxx
View profile  Send private message
timdw

Posts: 25
Posted: 06/04/2006, 8:10 AM

Sorry, typo:
$dodgychars = "[^0-9a-zA-z()_-]";
should be (with a capital Z):
$dodgychars = "[^0-9a-zA-Z()_-]";
View profile  Send private message

Add new topic Subscribe to topic   


These are Community Forums for users to exchange information.
If you would like to obtain technical product help please visit http://support.yessoftware.com.

MS Access to Web

Convert MS Access to Web.
Join thousands of Web developers who build Web applications with minimal coding.

CodeCharge.com

Home   |    Search   |    Members   |    Register   |    Login


Powered by UltraApps Forum created with CodeCharge Studio
Copyright © 2003-2004 by UltraApps.com  and YesSoftware, Inc.