manta has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

I'd like to loop through the form elements submitted to a cgi script and take different actions depending on the input type of the form element. Actually, I only need to tell the difference between input type = "file" and input type = "anything else". Is there a way to detect the input type of a param in CGI.pm? Basically, the trick is that I am trying to write a general pre-processing script that could be used with a number of different forms, so I don't want to rely on knowing the names of the input elements that have type = file.

Here's the rough outline of code for what I'm trying to do:

$query = CGI->new; @params = $query->param; foreach my $p (@params) { if( [$p is a file handle/input type == "file"] ) { [ read in from the file and do some stuff ] } else { [ do some other stuff ] } }

Thanks for your help!!

Replies are listed 'Best First'.
Re: Detect input type = file with CGI.pm
by ikegami (Patriarch) on Jun 24, 2010 at 23:18 UTC

    Where $param is a value returned by $cgi->param, this is how it's done internally:

    if (ref($param) && defined(fileno($param)) { is file } else { isn't }

    This should also work:

    if ($cgi->uploadInfo($param)) { is file } else { isn't }

    You only need to check if $cgi->content_type() eq 'multipart/form-data'.

      Hi,

      Thanks for your help. I did have to make one small change to the code you posted. For posterity, here's what I ended up with:

      if($query->uploadInfo($query->param($p))) { is file } else { isn't }
        Did you mistype something? That's the same thing I posted. Maybe it wasn't clear that $param is a value returned by param.