Should I restrict which characters are valid for a Filename as part of my “Upload a Photo” script?
I’m using Prepared Statements for all database actions, but am still wondering if there are characters in a Filename which could break something in my PHP script, MySQL Database, or elsewhere? :-/
Since you’re saving the info to a database, might I suggest that you save the filename in your database, then rename the file using the unique index of the file? For example, the index of the file is 20 in your database, you can rename original_file.jpg as file_20.jpg on your server; this way you won’t have to worry about filename issues.
// Create New File Path.
$newFilePath = WEB_ROOT . 'uploads/' . $newFilename;
// Create New Image.
switch ($imageType){
case IMAGETYPE_GIF:
$newPhoto = @imagegif($newTrueColorImage, $newFilePath);
break;
case IMAGETYPE_JPEG:
$newPhoto = @imagejpeg($newTrueColorImage, $newFilePath);
break;
case IMAGETYPE_PNG:
$newPhoto = @imagepng($newTrueColorImage, $newFilePath);
break;
default:
$newPhoto = FALSE;
}
So I suppose that covers things, although I still was wondering if certain special characters in the original file name could mess things up at the top of my script, like here…
// Check for File.
if (empty($_FILES['userPhoto']['tmp_name'])){
// No File.
$errors['upload'] = 'Choose a File.';
}else{
// File exists.
$tempFile = $_FILES['userPhoto']['tmp_name'];
}//End of CHECK FOR FILE
i would just be concerned about what is valid on the filesystem side. I wouldn’t throw an error, just be kind and rename / replace the invalid character for them.