Getting Blank Screen for Perl CGI Script - perl

I am getting blank screen for the below Perl CGI Script on the web page.
Script is getting executed fine on the terminal, but when I run it from the web browser it is blank. Please help.
This works when I move the Web Content to the top of the page. Basically whatever content I put after the DB connection is not getting displayed on the web browser.
OS : Unix
Apache2 Web Server
Note: The script has execute permission.
#!/usr/bin/perl
use strict;
use warnings;
use DBI;
use CGI;
print "Content-type: text/html\n\n";
# Simple HTML code follows
my $driver= "Oracle";
my $dsn = "DBI:$driver:sid=xxxxx;host=xxxxx;port=1521";
my $dbh = DBI->connect($dsn,'xxxx','xxxx');
#print $dbh;
my $sth = $dbh->prepare("SELECT * FROM TABLE WHERE ROWNUM <= 10");
$sth->execute;
print "<html> <head>\n";
print "<title>Hello, world!</title>";
print "</head>\n";
print "<body>\n";
print "<h1>Hello, world!</h1>\n";
print "<p>The Details are as follows:</p>\n";
print "<table cols=5 border=1>\n";
print "<tr>\n";
print "<th>ACTION</th>\n";
print "<th>ALARM_TEXT</th>\n";
print "<th>ALARM_SEV</th>\n";
print "<th>EMS_NAME</th>\n";
print "</tr>";
while( my $ref = $sth->fetchrow_hashref() ) {
print "<tr>\n";
print "<td>", $ref->{'ACTION'}, "</td>\n";
print "<td>", $ref->{'ALARM_TEXT'}, "</td>\n";
print "<td>", $ref->{'ALARM_SEV'}, "</td>\n";
print "<td>", $ref->{'EMS_NAME'}, "</td>\n";
print "</tr>\n";
}
print "</table>\n";
print "<h1>Hello, world!</h1>\n";
print "</body> </html>\n";

Fixed it by adding the below line to the httdd.conf file.
SetEnv ORACLE_HOME /oracle/app/oracle/product/11.2.0.4/db_1

Related

get request in perl and Use of uninitialized value

my $url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=journal+of+medical+virology[journal]+AND+2014[Date+-+Publication]:3000[Date+-+Publication]&usehistory=y";
print "\n before url \n";
print $url;
#post the esearch URL
my $output = get($url);
print $output;
I have not used perl ever before.
If I hit this URL in browser, I do get the XML.
However, From what I see in output from script, $output is empty and
print $output;
returns
Use of uninitialized value in print at ./extractEmails.pl line 48.
Please suggest what's wrong and how to fix it
Edit:
As suggested, complete code:
#!/usr/bin/perl -w
# A perlscript written by Joseph Hughes, University of Glasgow
# use this perl script to parse the email addressed from the affiliations in PubMed
use strict;
use LWP::Simple;
my ($query,#queries);
#Query the Journal of Virology from 2014 until the present (use 3000)
$query = 'journal+of+virology[journal]+AND+2014[Date+-+Publication]:3000[Date+-+Publication]';
push(#queries,$query);
#Journal of General Virology
$query = 'journal+of+general+virology[journal]+AND+2014[Date+-+Publication]:3000[Date+-+Publication]';
push(#queries,$query);
#Virology
$query = 'virology[journal]+AND+2014[Date+-+Publication]:3000[Date+-+Publication]';
push(#queries,$query);
#Archives of Virology
$query = 'archives+of+virology[journal]+AND+2014[Date+-+Publication]:3000[Date+-+Publication]';
push(#queries,$query);
#Virus Research
$query = 'virus+research[journal]+AND+2014[Date+-+Publication]:3000[Date+-+Publication]';
push(#queries,$query);
#Antiviral Research
$query = 'antiviral+research[journal]+AND+2014[Date+-+Publication]:3000[Date+-+Publication]';
push(#queries,$query);
#Viruses
$query = 'viruses[journal]+AND+2014[Date+-+Publication]:3000[Date+-+Publication]';
push(#queries,$query);
#Journal of Medical Virology
$query = 'journal+of+medical+virology[journal]+AND+2014[Date+-+Publication]:3000[Date+-+Publication]';
# global variables
push(#queries,$query);
my %emails;
my $emailcnt=0;
my $count=1;
#assemble the esearch URL
foreach my $query (#queries){
my $base = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/';
#my $url = $base . "esearch.fcgi?db=pubmed&term=$query&usehistory=y";
my $url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=journal+of+medical+virology[journal]+AND+2014[Date+-+Publication]:3000[Date+-+Publication]&usehistory=y";
print "\n before url \n";
print $url;
#post the esearch URL
my $output = get($url);
print "\n before output \n";
print get($url);
print $output;
#parse WebEnv, QueryKey and Count (# records retrieved)
my $web = $1 if ($output =~ /<WebEnv>(\S+)<\/WebEnv>/);
my $key = $1 if ($output =~ /<QueryKey>(\d+)<\/QueryKey>/);
my $count = $1 if ($output =~ /<Count>(\d+)<\/Count>/);
#retrieve data in batches of 500
my $retmax = 500;
for (my $retstart = 0; $retstart < $count; $retstart += $retmax) {
my $efetch_url = $base ."efetch.fcgi?db=pubmed&WebEnv=$web";
$efetch_url .= "&query_key=$key&retmode=xml";
my $efetch_out = get($efetch_url);
my #matches = $efetch_out =~ m(<Affiliation>(.*)</Affiliation>)g;
#print "$_\n" for #matches;
for my $match (#matches){
if ($match=~/\s([a-zA-Z0-9\.\_\-]+\#[a-zA-Z0-9\.\_\-]+)$/){
my $email=$1;
$email=~s/\.$//;
$emails{$email}++;
}
}
}
my $cnt= keys %emails;
print "$query\n$cnt\n";
}
print "Total number of emails: ";
my $cnt= keys %emails;
print "$cnt\n";
my #email = keys %emails;
my #VAR;
push #VAR, [ splice #email, 0, 100 ] while #email;
my $batch=100;
foreach my $VAR (#VAR){
open(OUT, ">Set_$batch\.txt") || die "Can't open file!\n";
print OUT join(",",#$VAR);
close OUT;
$batch=$batch+100;
}
I recommend against using LWP::Simple for any reason because it is impossible to configure it or handle errors usefully. Using LWP::UserAgent which it wraps is nearly as simple anyway (though the error handling is a bit complicated). The below examples would replace the use LWP::Simple; and my $output = get($url); lines.
use strict;
use warnings;
use LWP::UserAgent;
my $ua = LWP::UserAgent->new(timeout => 30);
my $response = $ua->get($url);
unless ($response->is_success) {
# the Client-Warning, Client-Aborted, and X-Died headers each may be set on client/transport errors
die $response->status_line;
}
my $output = $response->decoded_content;
The core HTTP::Tiny is also simple.
use strict;
use warnings;
use HTTP::Tiny;
my $ua = HTTP::Tiny->new;
my $response = $ua->get($url);
unless ($response->{success}) {
die $response->{status} == 599 ? $response->{content} : "$response->{status} $response->{reason}";
}
my $output = $response->{content};
If you really want an LWP::Simple approach that will at least report transport errors, try ojo from Mojolicious:
perl -Mojo -E'say g(shift)->text' http://example.com
In a script rather than a oneliner, you can use Mojo::UserAgent directly, and also handle HTTP errors like above:
use strict;
use warnings;
use Mojo::UserAgent;
my $ua = Mojo::UserAgent->new;
my $response = $ua->get($url)->result;
unless ($response->is_success) {
die $response->code . ' ' . $response->message;
}
my $output = $response->text;

How can I print the result of File::Find on html perl script?

I have to show the results from a search in a website. I'm receiving a search parameter from an html form. When I try this:
#!/usr/bin/perl
use CGI qw(:standard);
use File::Find;
my $search = param('value');
my $result = `print find(sub {print $File::Find::name if ($_ eq $search);
}, '/home');`
print "Content-type:text/html\n\n";
print "<html>";
print "<head></head>";
print "<body";
print "$result";
print "</body>";
print "</html>";
I get the following error:
syntax error at ./search.pl line 8, near "print"
Execution of ./search.pl aborted due to complication errors.
I think it's the assigning of find that's prompting the error. But I've tried other ways to no avail.
Your problem is back tick. Back tick only using for execute the linux commands.
print find(sub {print $File::Find::name if ($_ eq $search); }, '/home'); This is not a linux command. This is perl script.
So your script should be as follow
#!/usr/bin/perl
use CGI qw(:standard);
use File::Find;
my $search = param('value');
my $result;
find( sub { $result.=$File::Find::name if ($_ eq $search ); }, "/home");
print "Content-type:text/html\n\n";
print "<html>";
print "<head></head>";
print "<body>";
print "$result\n\n";
print "</body>";
print "</html>";
You want to execute the result in back tick run the perl one liner with -e -M switches. -e to execute the perl command. -M switch using for include the module in you oneliner. So which is should be as follow
#!/usr/bin/perl
use CGI qw(:standard);
my $search = param('value');
my $result = ` perl -MFile::Find -e 'print find(sub {print $File::Find::name if(/^$search\$/);}, "/home" )'`;
print "Content-type:text/html\n\n";
print "<html>";
print "<head></head>";
print "<body>";
print "$result";
print "</body>";
print "</html>";

Perl CGI download file

I need to create an HTML file which input text or file. The text will be processed and printed while the file is processed and downloaded.
I am not able to create download. I tried with download header, but it didn't work. A new file will be created with #array after processing the file. output_file.txt should be downloadable by the user.
#!C:/perl64/bin/perl.exe
use strict;
use warnings;
use CGI::Pretty qw(:all);
# HTML
print header();
print start_html();
print start_form();
print textfield('text');
print (submit);
print filefield('file');
print submit();
print end_form();
print end_html();
if (param ('file')) {
my $fh = param('file');
# File processed to get #result and made new file
open (OUT, ">output/output_file.txt");
print OUT #result;
# Need to download output_file.txt file
}
# Text processed and printed
elsif(param('text')){
my $text = param('text')
}
Try the following:
#!/usr/bin/perl -w
use strict;
use warnings;
use CGI::Pretty qw(:all);
my #result;
if (param ('file')) {
my $file_name=param('file');
my $file_handle =upload('file');
my $file_size=-s $file_handle;
print header(
-type=>'application/octet-stream',
-attachment=> $file_name,
-Content_Length=>$file_size
);
# file processed to get #result and made new file
binmode($file_handle);
while (<$file_handle>){
print $_;
push (#result,$_);
}
# need to download output_file.txt file
}
# text processed and printed
elsif(param('text')){
my $text = param('text');
print header(
-type=>'application/octet-stream',
-attachment=> "Sample.txt",
-Content_Length=>length($text)
);
print $text;
}
# html
print header();
print start_html();
print start_form();
print textfield('text');
print (submit);
print end_form();
print start_form();
print filefield('file');
print submit();
print end_form();
print end_html();
Here's an example I modified:
#!C:\Program Files\perl\bin\perl.exe
use CGI ':standard';
use CGI::Carp qw ( fatalsToBrowser );
$input_val = $ENV{'QUERY_STRING'};
($field_name, $command) = split (/=/, $input_val);
($file_name, $option_name) = split(/&/, $command);
$file_path= "Database/$file_name";
$directorypath = "Database/";
my $files_location;
my #fileholder;
$files_location = $directorypath;
if ($file_name eq '')
{
print "Content-type: text/html\n\n";
print "File doesn't exist";
} else {
open(DLFILE, "<$files_location/$file_name") || Error('open', 'file');
#fileholder = <DLFILE>;
close (DLFILE) || Error ('close', 'file');
print "Content-Type:application/x-download\n";
print "Content-Disposition:attachment;filename=$file_name\n\n";
print #fileholder;
}
print "</HTML>";
exit 0;
Refer to this website: http://www.perlnotes.com/study0680.htm

Perl HTTP::Request and Server Down

I have a perl script that is supposed to use HTTP::Response to grab an XML file and then parse it. The script works great, except when it can't reach the server its trying to get the info from.
I know I have to have an error checking and if an error does exist, use a return to continue on with the loop, I have done with with NET::SNMP and SSH, but I can't seem to get it working for this scenario. I'm about to be pull my hair in frustration. Any help is greatly appreciated.
#! /usr/bin/perl
use LWP::UserAgent;
use HTTP::Request::Common;
use Net::SNMP;
use XML::Simple;
use HTTP::Status;
$ua = LWP::UserAgent->new;
if ( open ( FH, "DeviceList.txt" ) )
{
while ( defined ( my $line = <FH> ) )
{
$line =~ s/\s+$//;
$device = $line;
&checkcon;
}
close FH;
}
else
{
print "DeviceList.txt file not found\n";
}
#exit;
sub checkcon
{
my ($req, $error) = HTTP::Request->new(GET => 'https://'.$device.'/getxml?location=/HelloWorld');
$ua->ssl_opts(SSL_verify_mode => SSL_VERIFY_NONE);
$ua->timeout(10);
$req->authorization_basic('test', 'test');
$test = $ua->request($req)->content;
print $req;
if ($test =~ "parser error") {
print "No Workie\n";
return;
}
#if (!is_success ($req))
#{
#print "No Workie!";
#return;
#}
# create object
my $xml = new XML::Simple;
# read XML file
my $data = $xml->XMLin("$test");
print "Looping";
# access XML data
`echo "$device,$data->{Hello}{World}{content}" >> Test.txt`;
}
exit 0;

Perl script for Downloading the file from web

I am trying to automate one of my task where i have to download a last 5 releases of some softwares let say Google talk from http://www.filehippo.com/download_google_talk/.
I have never done such type of programming i mean, to interact with Web through perl .I have just read and came to know that through CGI module we can implement this thing so i tried with this module.
If some body can give me better advice then please you are welcome :)
My code :
#!/usr/bin/perl
use strict;
use warnings;
use CGI;
use CGI::Carp qw/fatalsToBrowser/;
my $path_to_files = 'http://www.filehippo.com/download_google_talk/download/298ba15362f425c3ac48ffbda96a6156';
my $q = CGI->new;
my $file = $q->param('file') or error('Error: No file selected.');
print "$file\n";
if ($file =~ /^(\w+[\w.-]+\.\w+)$/) {
$file = $1;
}
else {
error('Error: Unexpected characters in filename.');
}
if ($file) {
download($file) or error('Error: an unknown error has occured. Try again.');
}
sub download
{
open(DLFILE, '<', "$path_to_files/$file") or return(0);
print $q->header(-type => 'application/x-download',
-attachment => $file,
'Content-length' => -s "$path_to_files/$file",
);
binmode DLFILE;
print while <DLFILE>;
close (DLFILE);
return(1);
}
sub error {
print $q->header(),
$q->start_html(-title=>'Error'),
$q->h1($_[0]),
$q->end_html;
exit(0);
}
In above code i am trying to print the file name which i wan to download but it is displaying error message.I am not able to figure it out why this error "Error: No file selected." is comming.
Sorry, but you are in the wrong track. Your best bet is this module: http://metacpan.org/pod/WWW::Mechanize
This page contain a lot of example to start with: http://metacpan.org/pod/WWW::Mechanize::Examples
It could be more elegant but I think this code easier to understand.
use strict;
use warnings;
my $path_to_files = 'http://www.filehippo.com/download_google_talk/download/298ba15362f425c3ac48ffbda96a6156';
my $mech = WWW::Mechanize->new();
$mech->get( $path_to_files );
$mech->save_content( "download_google_talk.html" );#save the base to see how it looks like
foreach my $link ( $mech->links() ){ #walk all links
print "link: $link\n";
if ($link =~ m!what_you_want!i){ #if it match
my $fname = $link;
$fname =~ s!\A.*/!! if $link =~ m!/!;
$fname .= ".zip"; #add extension
print "Download $link to $fname\n";
$mech->get($link,":content_file" => "$fname" );#download the file and stoore it in a fname.
}
}