且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何确定脚本是从命令行调用还是作为cgi脚本?

更新时间:2023-10-06 13:39:04

根据 RFC3875 (第4.1节)中的CGI规范。 4.),GATEWAY_INTERFACE环境变量是检查您是否在CGI上下文中运行的权威性操作:


4.1.4。 GATEWAY_INTERFACE



GATEWAY_INTERFACE 变量必须设置为CGI
的方言被服务器用来与脚本通信。



I have a script that I wrote that can either be used on the command line or as a CGI script, and need to determine how the script was called so I can output a content-type header for web requests (and maybe some anti-cache headers too). My first thought is to check for the existance of http environment variables:

my $js = build_javascript();

if ( exists $ENV{HTTP_HOST} ) {
   print "Content-type: text/javascript\n\n";
}
print $js;

Is there a better way?

According to the CGI specification in RFC3875 (section 4.1.4.), the GATEWAY_INTERFACE environment variable would be the authoritative thing to check whether you are running in a CGI context:

4.1.4. GATEWAY_INTERFACE

The GATEWAY_INTERFACE variable MUST be set to the dialect of CGI being used by the server to communicate with the script.