user2986042 user2986042 - 1 month ago 10
Ajax Question

Why file is not creating in CGI with Apache?

I want to write some contents to a file using CGI with Apache .

my HTML file :

using Ajax HTTP method to call CGI script . I am not passing any arguments to the CGI . Finally i am printing response text to a 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>


and cgi.cpp file

Here i creating a file with write mode , write some contents to that file and successfully close . Send response text "successfully write " to HTML back .

#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/html\n\n";
myfile << "Writing this to a file.\n";
cout<<"Sucessfully write";
myfile.close();

}
catch(exception& e) {

}

return 0;

}


But i can not see any file created in
/var/apache2
or in
/var/www/html
. Why this is happening ? Where should be a new file created ? is it in Apache directory ?

Any code problem ? I am writing to a file with write mode also . I think code is working fine . Any suggestions ?

Answer

Summary of previous comments:

  • Check privileges of your CGI file. Often there is a special user nobody which owns /var/www and which is used by Apache to execute scripts/processes.
  • Check if C++ CGI process is hit by Apache, does it return a response over HTTP.
  • Check what ofstream::is_open() returns, where it tries to create file. Good candidates to store created file by CGI process are /tmp and cgi-bin working directory (which is configured within httpd.conf), often it's /var/www/cgi-bin/
Comments