Use PHP - to serve TCL

tclbliss 03/04/2011

If your hosting provider does not offer Tcl and/or will not set up the Web server to serve Tcl CGI scripts, you can use PHP as a way to execute Tcl scripts: Create a new PHP file and put the following code in it:

<?php
ob_start();
$file = "./tst.tcl";
if (!getenv('request_method')) {
    global $HTTP_ENV_VARS;
    foreach($HTTP_ENV_VARS as $key => $val) {
        putenv("$key=$val");
    }
}
$out = shell_exec($file);
$out = split("\n\n", $out);
foreach (split("\n", $out[0]) as $v) {
        if (!$v) {continue;}
        header("$v");
}
print implode("", array_slice($out, 1));
ob_end_flush();
?>

Notice the $file = "./tst.tcl"; line? This is where you specify which Tcl script to run. In fact, you can run any script, not just Tcl.

In order for this to work, you absolutely have to return at least one HTTP header, which is "Content-Type" Example:

puts stdout "Content-Type: text/plain\n"
puts stdout "Hello World from Tcl CGI script"

Or, to serve an image file:

set fp [open /images/myphoto.jpg r]
chan configure $fp -translation binary -encoding binary
puts stdout "Content-Type: image/jpeg\n"
puts -nonewline stdout [read $fp]
close $fp

NOTE: this will not work if your hosting provider has disabled the exec() PHP function.

Also, if there is no Tcl installed on the server, you can still use TclKit, Freewrap or Cookit stand-alone Tcl binaries. All you need to do is upload them to your hosting provider and make them executable (chmod +x tclkit).


jblz - 2011-03-05 10:52:27

SLICK!


tclbliss 03/08/2011

Updated the script to test if the env variables are already present and to enable output buffering to prevent "headers already sent" error.