Weblog Navigation
First Previous Index Next Last
Perl CGI Upload Issue (Monday, April 11th, 2005)

Quick tip for anyone using CGI.pm to handle file uploads: with the new version of CGI, you need to make sure you're not creating multiple CGI objects (i.e. doing my $query=new CGI; more than once), or if you are, make sure the first one that gets created doesn't get destroyed until after you're done handling your file uploads. This is because when the CGI object gets destroyed (e.g. at the end of the block if it's local, or the end of your script if it's global), it deletes the temporary file used for the upload, and new CGI objects won't have access to the file anymore. When you try to call $query->upload('whatever') you'll get undef.

So, if you're moving a script from an old server to a new server, and you have CGI objects being created in multiple places (perhaps in multiple modules), you need to use a global like our $query=new CGI; for the first time a CGI object is created, and then either change all the others to just use the global $query instead of creating new local objects, or if you're lazy, leave them as-is (they should still work as long as they original doesn't get destroyed until after you're done).

It looks like this change was made as a workaround for the Win32 platform. Previously, temp files would be unlinked as soon as they were opened, so that as soon as they were closed they would be automatically deleted; on Win32 you can't unlink an open file, so they can't be unlinked until you're done with them.

Weblog Navigation
First Previous Index Next Last