question 464 Secure Python · medium
Allow only safe upload names
Sellers upload product photos and spec sheets, and the original file name is kept. Before a name is stored, check it against the shop's rules so it can never contain a path, a hidden-file name or an unexpected file type.
Function
upload_name_ok(name)Rules1 to 64 characters; only letters
A-Z/a-z, digits, _, - and .; must not start with .; exactly one ., followed by an extensionExtensions
jpg, jpeg, png or pdf, in any case (PNG is fine)Returns
True when every rule holds, otherwise FalseExamples
callupload_name_ok('SPO-11681_front.jpg')returnsTrue
callupload_name_ok('spec-sheet.PDF')returnsTrue
callupload_name_ok('../../etc/passwd')returnsFalse
callupload_name_ok('photo.png.exe')returnsFalse