为什么文件不能在Apache的CGI中创建

Why file is not creating in CGI with Apache?

本文关键字:CGI 创建 Apache 文件 不能 为什么      更新时间:2023-10-16

我想用Apache的CGI写一些内容到一个文件。

我的HTML文件:

使用Ajax HTTP方法调用CGI脚本。我没有给CGI传递任何参数。最后,我打印响应文本到一个div。

<!DOCTYPE html>
<html>
<head>
<script>
var xhttp;
function loadDoc() {
    try{
          xhttp = new XMLHttpRequest();
          xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                     document.getElementById("message").innerHTML = this.responseText;
                }
          };
          xhttp.open("POST","mycgi.cgi",true);
          xhttp.send();

    }catch (exception){
            alert("Request failed: " + exception.message);
        }
}
</script>
</head>

<body>
<h2>sample ajax</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
<div id ="message" />
</body>
</html>

cgi.cpp文件

这里我创建了一个写模式的文件,将一些内容写入该文件并成功关闭。发送响应文本"成功写入"返回到HTML。

    #include <unistd.h>
    #include <iostream>
    #include <vector>
    #include <string>
    #include "cgicc/Cgicc.h"
    #include "cgicc/HTTPHTMLHeader.h"
    #include "cgicc/HTMLClasses.h"
    #include <stdio.h>
    #include <string.h>
    #include <fstream>
    using namespace std;
    using namespace cgicc;
    int main(int argc, char **argv)
    {
    Cgicc cgi;    
       try {
        ofstream myfile;
        myfile.open ("Newcgi.txt",ios::out);
        cout<<"Content-Type: text/htmlnn";
        myfile << "Writing this to a file.n";
        cout<<"Sucessfully write";
        myfile.close();
       }
       catch(exception& e) {
       }
     return 0;
    }

但是我看不到在/var/apache2/var/www/html中创建的任何文件。为什么会发生这种情况?应该在哪里创建新文件?是在Apache目录下吗?

代码有问题吗?我也正在写一个文件与写模式。我认为代码工作得很好。有什么建议吗?

前文总结:

    检查你的CGI文件的权限。通常有一个特殊的用户nobody拥有/var/www, Apache使用它来执行脚本/进程。
  • 检查c++ CGI进程是否被Apache击中,它是否通过HTTP返回响应。
  • 检查ofstream::is_open()返回的内容,它试图创建文件的位置。/tmpcgi-bin工作目录(在httpd.conf中配置)是存储CGI进程创建的文件的好候选目录,通常是/var/www/cgi-bin/