简体   繁体   English

Perl CGI脚本的环境变量

[英]Environment variable for perl cgi scripts

I have a cgi script similar to the following: 我有一个类似于以下内容的cgi脚本:

BEGIN {
    unshift (@INC, "$ENV{'HOME'}/www/cgi-bin/SiteSpecific");
}

print "Content-type: text/html\n\n";
use SiteObject;
my $siteObjInst = SiteObject->instance();
print $siteObjInst->{HideFields};

This would run fine from the command prompt, but fails when run as a CGI script from a browser. 这在命令提示符下可以正常运行,但是当从浏览器作为CGI脚本运行时失败。 The $ENV{'HOME'} is perhaps not set as the script cannot find the module. 可能未设置$ ENV {'HOME'},因为脚本无法找到该模块。

Is it that the CGI scripts are not run within a shell and do not find the environment variables? 是不是CGI脚本没有在shell中运行并且没有找到环境变量?

If the above is true, do I need to set the desired variables within the BEGIN block using some other means? 如果上述情况成立,是否需要使用其他方法在BEGIN块中设置所需的变量?

Thanks for your help. 谢谢你的帮助。

A CGI program will have its environment set by the web server. 一个CGI程序将由Web服务器设置其环境。 HOME may or not be set depending on how your web server is set up, and if it is set it will probably point to the home directory of the user that the web server is running as, not your home directory. 可以根据是否设置Web服务器来设置是否设置HOME,如果设置了HOME,则可能会指向运行该Web服务器的用户的主目录,而不是您的主目录。

You can print the value of $ENV{HOME} from the CGI program, or even better, print the entire %ENV hash to see what's really happening. 您可以从CGI程序中打印$ ENV {HOME}的值,甚至更好的是,打印整个%ENV哈希值以查看实际情况。

In my experience its better to either hardcode the full path to extra libraries or set the path externally (eg using PERL5LIB). 以我的经验,最好将完整路径硬编码为额外的库,或者在外部设置路径(例如,使用PERL5LIB)。 If you're setting it from inside the program, use the "lib" pragma rather than modifying @INC directly: 如果要在程序内部进行设置,请使用“ lib”编译指示,而不要直接修改@INC:

use lib '/home/user/www/cgi-bin/siteSpecific';

You definitely can't guarantee that your shell and the id running the web server have the same variable for $ENV{HOME} . 您绝对不能保证$ENV{HOME}外壳程序和运行Web服务器的ID具有相同的变量。 Forget all of that code for a little while and try this: 暂时忘记所有代码,然后尝试以下操作:

print "Content-type: text/html\n\n";
print  q[<html><head><title>A Page</title></head>]
    . qq[<body><h1>\$HOME=$ENV{HOME}</h1></body></html>]
    ;

Or even this: 甚至这个:

use strict;
use warnings;
use CGI;

my $q = CGI->new;
print $q->header
    , $q->start_html( 'A Page' )
    , $q->start_table
    , $q->Tr( $q->th( 'Name' ), $q->th( 'Value' ))
    , ( map { $q->Tr( $q->td( $_ ), $q->td( $ENV{$_} )) } sort keys %ENV )
    , $q->end_table
    , $q->end_html
    ;

For a list of some issues and potential answers, I'd start with How can I troubleshoot my Perl CGI script? 要获取一些问题和可能的答案的列表,请从如何对Perl CGI脚本进行故障排除开始 .

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

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