How to upload and open a file in xampp apache server using CGI Perl Script?

前端 未结 1 1771
无人及你
无人及你 2021-01-25 19:43

This code works fine in my local xampp apache server. I run the same code in local area network with different ip addressed system. The file cannot open and i cant write it to t

相关标签:
1条回答
  • 2021-01-25 20:17

    Getting the filename from the input parameter ("xml" in this case) is always a really bad idea. Browsers differ in their behaviour. Some give you the full filename, some only give you the basename. When they give you the full path, it will be the path on the client computer - a path that is pretty much guaranteed not to exist on your server. [Update: And re-reading your question, I realise that's exactly why it works when you're testing it locally.]

    There's a detailed explanation of how to do this in the documentation for the CGI module. You should really read all of that section before writing your code. But in summary.

    # Get the filename which may well include a path and which
    # should never be used as a filename on the server.
    my $filename = $cgi->param('xml');
    
    # Try to calculate a local filename
    my $local_fn;
    if ($filename =~ /([-\w\.]+)$/) {
      $local_fn = $1;
    }
    
    # Get file handle to uploaded file
    my $local_in_fh = $cgi->upload('xml');
    
    # Open a file handle to store the file
    open $local_out_fh, '>', "/path/to/output/dir/$local_fn" or die $!;
    
    while (<$local_in_fh>) {
      # process one line from the input file (which is in $_)
      print $local_out_fh;
    }
    

    There are a couple of other things that might be useful for you.

    $cgi->uploadInfo($filename)->{'Content-Type'} will give you the MIME type of the uploaded file. You can use that to work out how you want to process the file.

    $cgi->tmpFileName($filename) will give you the path to the temp file where your data has been uploaded. This will be deleted when the CGI program exits. But if you just want to save the file without processing it in any way, you can just move this file to a new location on your server.

    Some other notes about your existing solution:

    1. Your first program just displays a HTML file. So why not have a static HTML file?
    2. $CGI::POST_MAX does nothing.
    3. Please use CGI->new instead of new CGI.
    4. You create two CGI objects ($query and $cgi). You only need one.
    5. You print the CGI header twice.
    6. DATA is a special file handle name. You shouldn't use it for your own file handles.
    7. $lines = <DATA> will only get the first line from the file.
    8. open(OUT, '>dirname($file)."\\out_".basename($file)') isn't doing anything like what you think it's doing.
    0 讨论(0)
提交回复
热议问题