通过cgi / perl中的重定向传递变量

时间:2014-07-09 17:35:49

标签: perl redirect cgi

我有两个cgi脚本。 Login.cgi和welcome.cgi 我想在这两个页面之间传递变量 这是我有两个页面

#!C:/Perl/bin/perl.exe -w
#login.cgi
use strict;
use warnings;

use CGI::Pretty qw(:all);

my $cgi      = new CGI;
my $username = $cgi->param('username');
my $password = $cgi->param('password');

if ( ( $cgi->param('username') eq 'demo' ) && ( $cgi->param('password') eq 'demo' ) ) {
    print $cgi->redirect("welcome.cgi");
}
else {
    print header();
    print start_html( -title => "Login" );
    if ( $cgi->param('username') or $cgi->param('password') ) {
        print center( font( { -color => 'red' }, "Invalid input" ) );
    }
    print generate_form();
    print end_html();
}

sub generate_form {
    return start_form,
      h1("Please Login"),
      p( "username", textfield('username') ),
      p( "password", textfield('password') ), p(submit),
      end_form;
}

另一页welcome.cgi

#!C:/Perl/bin/perl.exe -w
#welcome.cgi
use warnings;
use CGI::Pretty qw(:all);
use strict;
my $cgi=new CGI;
my $username;
print header();
print start_html("Welcome"),h1("Hello, $username");
print end_html();

如何将用户名变量传递给welcome.cgi?

3 个答案:

答案 0 :(得分:1)

您可以直接传递(通过在query string中对其进行编码并将其添加到您要重定向到的网址),也可以将其存储在cookiesession中然后在另一个脚本中检索它。

答案 1 :(得分:1)

使用CGI::Session

有关在脚本之间传递信息的所有不同方法的教程以及为什么此实现是一个不错的选择,请阅读CGI::Session::Tutorial

在您的登录脚本中实施:

#login.cgi
use strict;
use warnings;

use CGI::Pretty qw(:all);
use CGI::Session;

my $cgi      = new CGI;
my $session  = CGI::Session->new($cgi) or die CGI->Session->errstr;
my $username = $cgi->param('username') // '';
my $password = $cgi->param('password') // '';

if ( $username eq 'demo' && $password eq 'demo' ) {
    $session->param(username => $username);
    print $cgi->redirect("welcome.cgi");
    exit;
}

print $session->header();
print start_html( -title => "Login" );
if ( $username or $cgi->param('password') ) {
    print center( font( { -color => 'red' }, "Invalid input" ) );
}
print start_form,
  h1("Please Login"),
  p( "username", textfield('username') ),
  p( "password", textfield('password') ), p(submit),
  end_form,
  end_html();

在你的欢迎剧本中:

#welcome.cgi
use strict;
use warnings;

use CGI::Pretty qw(:all);
use CGI::Session;

my $cgi      = new CGI;
my $session  = CGI::Session->new($cgi) or die CGI->Session->errstr;

my $username = $session->param('username');

print header();
print start_html("Welcome"),h1("Hello, $username");
print end_html();

答案 2 :(得分:0)

我不得不在这里略微不同意米勒先生。 CGI :: Session目前在很多方面已经过时,特别是由于:

  1. 设置Cookie的方法已过时,并且不符合RFC6265
  2. Cookie ID算法不够安全,作者已转移到其他项目。
  3. 因此除非出于教育目的,否则不应使用。

    关于原始问题,您可以查看这个简单的教程 http://practicalperl5.blogspot.in/2014/07/perl-login-script.html