phpstringtclpassthru

How to pass the string from php to tcl and execute the script


I want to pass the string from my php like

<?php
str1="string to pass"
#not sure about passthru
?>

And my tcl script

set new [exec $str1]#str1 from php
puts $new

Is this Possible? Please let me know I'm stuck with this


Solution

  • The simplest mechanism is to run the Tcl script as a subprocess that runs a receiving script (that you'd probably put in the same directory as your PHP code, or put in some other location) which decodes the arguments it is passed and which does what you require with them.

    So, on the PHP side you might do (note the important use of escapeshellarg here! I advise using strings with spaces in as test cases for whether your code is quoting things right):

    <?php
    $str1 = "Stack Overflow!!!";
    $cmd = "tclsh mycode.tcl " . escapeshellarg($str1);
    $output = shell_exec($cmd);
    echo $output;
    echo $output;
    ?>
    

    On the Tcl side, arguments (after the script name) are put in a list in the global argv variable. The script can pull them out with any number of list operations. Here's one way, with lindex:

    set msg [lindex $argv 0]
    # do something with the value from the argument
    puts "Hello to '$msg' from a Tcl script running inside PHP."
    

    Another way would be to use lassign:

    lassign $argv msg
    puts "Hello to '$msg' from a Tcl script running inside PHP."
    

    Note however (if you're using Tcl's exec to call subprograms) that Tcl effectively automatically quotes arguments for you. (Indeed it does that literally on Windows for technical reasons.) Tcl doesn't need anything like escapeshellarg because it takes arguments as a sequence of strings, not a single string, and so knows more about what is going on.


    The other options for passing values across are by environment variables, by pipeline, by file contents, and by socket. (Or by something more exotic.) The general topic of inter-process communication can get very complex in both languages and there are a great many trade-offs involved; you need to be very sure about what you're trying to do overall to pick an option wisely.