使用CGI-perl将发布数据写入文件

时间:2015-03-04 11:05:20

标签: perl cgi server

我正在使用纯html / javascript开发客户端程序,它可以将文件夹,文件及其内容作为paramaters发送到目标cgi脚本的post请求中(即saveFile.cgi)。

我可以从帖子请求中检索数据,但我无法使用脚本中的这些表单数据创建文件/文件夹,但我可以使用print打印这些值。

此外,我能够使用我试图从帖子请求中检索的确切字符串文字来创建文件/文件夹。我不知道我哪里出错了。

我在windows环境中编程:

客户代码:

var data = {
             "folder": variant,
             "file"  : "metadata.json",
             "content": response
           };

           $.post('../cgi-bin/demos/saveJSON.cgi', data, function(resp) {
                  // Do something with the request
           }, 'json');

服务器端/ CGI脚本:

#!C:\perl\bin\perl.exe -wT
    use CGI;
    use JSON;

    print "Content-type: text/html\n\n";

    $query = new CGI;

    $folder  = $query->param("folder");
    $file    = $query->param("file");
    $content = $query->param("content");

    #print "Folder " . $folder ."<br/>";
    #print "File " . $file ."<br/>";
    #print "Content " . $content ."<br/>";

    mkdir($folder, 0700) unless(-d $folder);
    open(OS,">$folder/$file") or die("Cannot write to file");
    print OS $content;
    close(OS);

2 个答案:

答案 0 :(得分:1)

  

我无法使用这些表单数据创建文件/文件夹   脚本,但我能够使用print

打印这些值

几乎可以肯定,问题是您的Web服务器没有权限在您尝试创建文件的目录中创建文件。您可以通过改进open()调用的错误检查并查看Web服务器错误日志来检查该理论。

# $! contains the details of the error
open(OS,">$folder/$file") or die("Cannot write to file '$folder/$file': $!");

然后,您必须更改处理,以便写入具有正确权限的目录。

其他一些建议。

  • 始终包含use strictuse warnings
  • 使用my $query = CGI->new而不是$query = new CGI
  • 使用词法文件句柄和open()的三个参数
    • open my $os_fh, '>', "$folder/$file" or die "..."
  • 考虑从CGI转移到像Dancer这样的现代解决方案。

答案 1 :(得分:-1)

我不知道您是否可以在服务器上安装模块。如果是的话,我肯定会建议你使用一些抽象层,比如IO :: All。

...
$folder  = $query->param("folder");
$file    = $query->param("file");
$content = $query->param("content");

# very minimal folder and filename sanitizing: allow only 
# alphanumeric characters. No slashes!
$folder =~ s{[^a-z0-9_\-.]}{}gi;
$file   =~ s{[^a-z0-9_\-.]}{}gi;

use IO::All;
io( $folder )->mkdir;
io( "$folder/$file" ) < $content; # yes, the < is like "put into"

关于IO :: All的一个很酷的事情就是隐藏文件句柄,缓冲区等的处理,当出现问题时会出错 - 就像无法创建目录一样。

请参阅:IO::All on metacpan

消毒是非常小的,并且不允许子目录,但是你不希望任何人写一些像

这样的东西
{ 
    folder:  "/var/www-data/.evil", 
    file:    "hacker.zip",
    content: "..someting really evil.."
}

将其上传到您的服务器。

无论如何,要安装IO :: All使用

cpan IO::All

或在Debian / Ubuntu上

sudo apt-get install libio-all-perl