简体   繁体   English

如何从Perl CGI脚本读取Web服务器上的文件,然后打印数据?

[英]How do I read a file on my webserver from my Perl CGI script and then print the data?

I have a file "a.cpm" on my webserver. 我的网络服务器上有一个文件“ a.cpm”。 I have a handler that when you go to asdasd.com/a.cpm it starts the CGI perl script. 我有一个处理程序,当你去asdasd.com/a.cpm它启动CGI perl脚本。 I have tried reading the file then printing the data but it doesnt do anything. 我尝试读取文件,然后打印数据,但是它什么也没做。

#!/usr/bin/perl
print "Content-type:text/html\r\n\r\n";
print "test string";
print "<br>";
$filepath = $ENV{'PATH_TRANSLATED'};
open FILE, $filepath or die $!;
my @lines = <FILE>;
while (my $line = <FILE>) 
{
print $_;
}

Have you read brian d foy 's How can I troubleshoot my Perl CGI script? 您是否阅读过brian d foy的? 如何解决我的Perl CGI脚本问题? and followed through with its suggestions? 并遵循其建议?

The accepted answer does not work out of the box -- here is a slight variation that does -- just adjust the path to file.txt : 接受的答案不是开箱即用的-这是一个很小的变化-只需调整file.txt的路径即可:

#!/usr/bin/perl
use CGI qw(:standard);
print <<HTML;
Content-type: text/html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head><title>Path Translated</title></head>
<body>
HTML

open FILE, "file.txt" or die "could not open filename";
while(<FILE>) {
    print $_;
}
close FILE;

print <<HTML;   
</body>
</html>
HTML

If your handler is working fine and you have changed the file permissions chmod a+x of your CGI script, then I suggest using the CGI module as shown in the code below. 如果您的处理程序工作正常,并且您已更改了CGI脚本的文件权限chmod a+x ,则建议使用CGI模块,如下面的代码所示。

#!/usr/bin/perl
use CGI qw(:standard);
print <<HTML;
Content-type: text/html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head><title>Path Translated</title></head>
<body>
HTML

$filepath = $ENV{'PATH_TRANSLATED'};
open FILE, $filepath or die $!;
my @lines = <FILE>;
while (my $line = <FILE>) 
{
    print $_;
 }

print <<HTML;   
</body>
</html>
HTML

EDIT : Taint checking, turning on the warnings and using strict are good practice, more so for web applications. 编辑 :污点检查,打开警告和使用严格是良好的做法,更适用于Web应用程序。

#!/usr/bin/perl -wT
use strict;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM