I know the golden rule, never trust user supplied filenames. I want to break that rule though. Is there anything unsafe about the following scheme?
$name = $_POST['name'];
$id = intval($_GET['id']);
$sanitized_name = preg_replace('/[^0-9a-zA-Z]/','',$name);
$fp = fopen("/path/to/".$id."/".$sanitized_name.".jpg",'w');
If I replace everything that is NOT 0-9 or a-z or A-Z with '' then there's absolutely 0% change anyone can inject a '.' to create their own extension (with the combination of a NULL byte) or traverse a directory. This seems safe. I just wanted to run it by SO.
Also since the ID is forced to be an int, anything funky will simply turn into a 0.
If by secure you mean the user can't force upload in another folder or for another extension, yeah, this is good.
Addtionnaly, for making the filename "more unique", you can add a timestamp time()
and / or a random number rand(0, MAX)
in the filename.