As everyone will tell you, this is risky. The safest way I can think of to do it is to have the CGI program mark images as 'deleted' in a database or other persistent file, and have a batch script run every night to remove images that have been marked for deletion.
The key point is to separate the actual file removal code into a script that can't be run as a CGI