Running a CGI script from html in a Mac Server

771 views Asked by At

I have the following code located in /Library/WebServer/Documents/ and cgi code in /Library/WebServer/Documents/cgi-bin/bot_stop.cgi

Html code:

<button style="height: 75px; width: 85px" onclick="bot_stop()">
    <img style="height: 63px"src="http://images.clipartpanda.com/stop-sign-clipart-119498958977780800stop_sign_right_font_mig_.svg.hi.png">
</button>

XMP code:

function bot_stop()
{
    xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET","cgi-bin/bot_stop.cgi",true);
    xmlhttp.send();
    alert("I am an alert box!");
}

CGI code:

#!/bin/bash

echo hello world

How do I know that the script ran? Also I receive the popup but know way knowing that the function above worked.

1

There are 1 answers

5
daxim On

You have bitten off more than you can chew at once. I'll try to help you with the first part.

For trouble-shooting, it is best to reduce complexity. Instead of making an XHR in the browser, you will first make an HTTP request in the command-line which is a much more simple matter.

Install curl. Homebrew has the newest version. Run curl -v http://localhost/cgi-bin/bot_stop.cgi.

If you get Connection Refused, then the Web server is not running or it's running on a port different than 80. Restart it or look into the Web server configuration what the configured port is. For example, if it's 8080, then you need to run curl -v http://localhost:8080/cgi-bin/bot_stop.cgi instead.

If you get a Not Found error, or "The system cannot find the file specified", then the Web server is not correctly configured to run CGI programs from that location. Read the Web server documentation how to change the configuration to run CGI programs from the location /Library/WebServer/Documents/cgi-bin/.

If you get an Internal Server error, look into the Web server error log. If it says "cannot exec: Permission denied", then you need to set the executable file attribute on your CGI program. If it says "Premature end of script headers", then the CGI program was able to run, but did not return a correct enough HTTP response. Since you use bash, you need to construct the HTTP header yourself:

#!/bin/bash
echo Content-Type: text/plain
echo
echo hello world

With Perl, a CGI program looks rather like this:

#!/usr/bin/env plackup
use strict;
use warnings;
my $app = sub {
    return [
        200,
        ['Content-Type' => 'text/plain'],
        ['hello world'],
    ];
};

And a successful curl response should look similar to:

< HTTP/1.1 200 OK
< Date: Tue, 13 Feb 2018 09:03:25 GMT
< Server: blahblahblahblah
< Content-Length: 12
< Content-Type: text/plain
<
hello world

Now that you know this works, you can use the URL in the browser address bar, and then try to make an XHR triggered by a button. Use the Developer tools/Javascript console to check for error details.