liamzebedee
liamzebedee

Reputation: 14490

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. I have a handler that when you go to asdasd.com/a.cpm it starts the CGI perl script. 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 $_;
}

Upvotes: 0

Views: 4292

Answers (3)

lawlist
lawlist

Reputation: 13457

The accepted answer does not work out of the box -- here is a slight variation that does -- just adjust the path to 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

Upvotes: 0

cjm
cjm

Reputation: 62109

Have you read brian d foy's How can I troubleshoot my Perl CGI script? and followed through with its suggestions?

Upvotes: 2

Philar
Philar

Reputation: 3897

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.

#!/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.

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

Upvotes: 0

Related Questions