cgi perl script to list subdirectories and files
I searched from internet, but I only found php solutions to this problem. Please help if you know how to do this in perl.
I am trying to generate a开发者_如何学JAVA webpage showing the content of a directory on my server's local disk. For example, a page containing the following will do the work
<file name="file1" href="file1" />
<dir name="dir1" href="dir1/" />
<dir name="dir2" href="dir2/" />
Thank you for your help.
Modifications have to be made to secure the script and also in jailing it. However, the idea can be implemented like:
#!/usr/bin/perl -T
use strict;
use warnings;
use CGI;
use File::Basename;
use File::Spec;
use Path::Trim;
my $cgi = CGI->new();
if ( my $file = $cgi->param('file') ) {
open my $fh, '<', $file or die $!;
print $cgi->header(
'-type' => 'application/octet-stream',
'-attachment' => basename($file),
'-Content_Length' => -s $file,
);
binmode $fh;
print while <$fh>;
}
else {
my $path = $cgi->param('path');
print $cgi->header(), $cgi->start_html();
# remove redundant current directory and parent directory entries
my $pt = Path::Trim->new();
$pt->set_directory_separator('/');
$path = $pt->trim_path($path);
# remove all ../ and ./ that have accumulated at the beginning of the path and
# make the path absolute by prepending a /
$path =~ s{^ (\.\.? /)+ }{}x;
$path = "/$path" unless $path =~ m{^ / }x;
print $cgi->h1($path);
opendir my $dh, $path or die $!;
my @entries = grep { $_ !~ /^ \. $/x } readdir $dh;
closedir $dh;
print $cgi->start_ul();
for my $entry ( sort { $a cmp $b } @entries ) {
if ( -d File::Spec->catfile( $path, $entry ) ) {
my $abs_entry = File::Spec->catfile( $path, $entry );
my $anchor = $cgi->a( { 'href' => "?path=$abs_entry" }, $entry );
print $cgi->li($anchor);
}
else {
my $abs_entry = File::Spec->catfile( $path, $entry );
my $anchor = $cgi->a( { 'href' => "?file=$abs_entry" }, $entry );
print $cgi->li($anchor);
}
}
print $cgi->end_ul(), $cgi->end_html();
}
This should get you started:
#!/usr/bin/perl -Tw
use 5.008_001;
use strict;
use warnings;
print "Content-Type: text/html; charset=utf-8\r\n\r\n";
print <<EOF;
<html>
<head>
<title>Directory Listing</title>
</head>
<body>
<pre>
EOF
opendir(my $dir, ".");
foreach(sort readdir $dir) {
my $isDir = 0;
$isDir = 1 if -d $_;
$_ =~ s/&/&/g;
$_ =~ s/"/"/g;
$_ =~ s/</</g;
$_ =~ s/>/>/g;
my $type = "[ ]";
$type = "[D]" if $isDir;
print "$type<a href=\"$_\" title=\"$_\">$_</a>\n";
}
print <<EOF;
</pre>
</body>
</html>
EOF
精彩评论