Using proc_open function in PHP - php

I am trying to execute a TCL script from PHP. I am using PHP's proc_open for the communication .But I am unable to get the result from the tcl script .
Can someone go through the code and let me know where I am going wrong ?
PHP code
<?php
$app = 'tclsh84.exe';
$spec = array(array("pipe", "r"), array("pipe", "w"), array("pipe", "w"));
$process = proc_open($app, $spec, $pipes);
if (is_resource($process))
{
fwrite($pipes[0], 'source sum.tcl ');
fwrite($pipes[0], 'tclsh test.tcl ');
fclose($pipes[0]);
echo stream_get_contents($pipes[1]);
fclose($pipes[1]);
// echo fread($pipes[1],1024).'<hr>';
proc_close($process);
}
?>
//sum.tcl
proc sum {arg1 arg2} {
set x [expr {$arg1 + $arg2}];
return $x
}
//test.tcl
puts " the sum is [sum 10 9 ] "

You're not passing newlines to the application (fwrite($pipes[0], "source sum.tcl\n")), could that be the cause? Otherwise make sure to check all return values of your function calls. You should fail early, if the first fwrite() fails, for example.

Related

PHP - `shell_exec` not working with NMap (Windows Server)

I've been trying to figure out why I can't get NMap to give me any sort of output nor even work for that matter via PHP.
Things I've tried so far:
// this doesn't return anything because it's wrong
$output = passthru('nmap -V');
echo $output;
// this returns a negated integer value
passthru('nmap -V', $output);
echo $output;
// this doesn't return anything either
$stream = popen('C:\nmap -V', 'r');
while (!feof($stream))
{
$buffer = fread($stream, 1024);
echo $buffer;
}
pclose($stream);
// this doesn't do anything as well
$output = system('C:\nmap -V');
echo $output;
// this does nothing also...
ob_start(); // start output buffering
fpassthru('C:\nmap -V'); // flush COMPLETE output of nmap
$output = ob_get_contents(); // capture output buffer contents
ob_end_clean(); // shutdown output buffers
echo $output; // echo it
.
// okay, how about we try a 'proc_open()'?
// nope, this doesn't work either. I just get a value of "command returned -1073741515"
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("file", "errors/errors.txt", "a") // stderr is a file to write to
);
$cwd = 'errors';
$env = array('some_option' => 'aeiou');
$process = proc_open('C:/nmap -V', $descriptorspec, $pipes, $cwd, $env);
if (is_resource($process))
{
// $pipes now looks like this:
// 0 => writeable handle connected to child stdin
// 1 => readable handle connected to child stdout
// Any error output will be appended to /errors/errors.txt
fwrite($pipes[0], '<?php print_r($_ENV); ?>');
fclose($pipes[0]);
echo stream_get_contents($pipes[1]);
fclose($pipes[1]);
// It is important that you close any pipes before calling
// proc_close in order to avoid a deadlock
$return_value = proc_close($process);
echo "command returned $return_value\n";
}
And many others, but I get absolutely NOTHING back from $output. I've done a lot of Google searching too, but I still can't figure it out. Many examples also seem to be for Linux which doesn't help.
Thanks.
Okay, I get an output using this code. I will continue coding and finish the rest of the program. Thanks to 'Chris Haas' for the suggestion in using proc_open
NOTE: The directory that contains the 'errors.txt' file must have 'IIS_IUSRS' write permissions. When in doubt, check your PHP error log.
$descriptorSpec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("file", "errors/errors.txt", "a") // stderr is a file to write to
);
$env = array('bypass_shell' => true);
$process = proc_open("NMAP.EXE -V", $descriptorSpec, $pipes, "C:\\Program Files (x86)\\NMap", $env);
if (is_resource($process))
{
// '$pipes' now looks like this:
// 0 => writeable handle connected to child stdin
// 1 => readable handle connected to child stdout
fwrite($pipes[0], '<?php print_r($_ENV); ?>');
fclose($pipes[0]);
echo stream_get_contents($pipes[1]);
fclose($pipes[1]);
// it is important that you close any pipes before calling
// proc_close in order to avoid a deadlock
$return_value = proc_close($process);
echo "<br /><br />Command Returned: $return_value\n";
}
Nmap version 7.91 ( https://nmap.org ) Platform:
i686-pc-windows-windows Compiled with: nmap-liblua-5.3.5
openssl-1.1.1h nmap-libssh2-1.9.0 nmap-libz-1.2.11 nmap-libpcre-7.6
Npcap-1.00 nmap-libdnet-1.12 ipv6 Compiled without: Available nsock
engines: iocp poll select
Command Returned: 0

Is there any way to give user input one by one to a running .exe file in php

I want to run .exe file from php. It asks for user input one by one. Is there any way I can do this.
I tried using shell_exec(), exec() but they didn't return the expected results.
I found a solution for my own query, please find the piece of code below that solved the purpose:
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("file", "error.txt", "a")
);
$process = proc_open('xyz.exe', $descriptorspec, $pipes);
$input1 = "1";
if (is_resource($process)) {
print fgets($pipes[1]); // this will help you read the lines
fwrite($pipes[0], $input1."\n"); // to provide input
print fgets($pipes[1]);
fclose($pipes[1]);
fclose($pipes[0]);
$return_value = proc_close($process);
echo "command returned $return_value\n";
} else {
echo "Resource unavailable";
}

PHP SVN update - TortoiseSVN

New code:
<?php
exec('"C:\Program Files\TortoiseSVN\bin\svn.exe" update "c:\wamp\www\project"');
This results in an infinite loop, no result is returned. What am I doing wrong?
== edit ==
On Windows, I'm trying to update a project by using PHP. I'm having problems using the commandline: I want visual feedback (important in case of conflicts), so I don't want to start as a background process. Is this possible?
The code I have so far is:
<?php
$todo = "cd \"C:\\Program Files\\TortoiseSVN\\bin\\\"";
$todo2 = "START TortoiseProc.exe /command:update /path:\"C:\\wamp\\www\\project\\\" /closeonend:0";
pclose(popen($todo, "r"));
pclose(popen($todo2, "r"));
I would drop exec and use proc_open (see http://php.net/manual/en/function.proc-open.php)
Here's an example I quickly whipped up and which should work for you:
<?php
// setup pipes that you'll use
$descriptorspec = array(
0 => array("pipe", "r"), // stdin
1 => array("pipe", "w"), // stdout
2 => array("pipe", "w") // stderr
);
// call your process
$process = proc_open('"C:\Program Files\TortoiseSVN\bin\svn.exe" update "c:\wamp\www\project"',
$descriptorspec,
$pipes);
// if process is called, pipe data to variables which can later be processed.
if(is_resource($process))
{
$stdin = stream_get_contents($pipes[0]);
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
$return_value = proc_close($process);
}
// Now it's up to you what you want to do with the data you've got.
// Remember that this is merely an example, you'll probably want to
// modify the output handling to your own likings...
header('Content-Type: text/plain; charset=UTF-8');
// check if there was an error, if not - dump the data
if($return_value === -1)
{
echo('The termination status of the process indicates an error.'."\r\n");
}
echo('---------------------------------'."\r\n".'STDIN contains:'."\r\n");
echo($stdin);
echo('---------------------------------'."\r\n".'STDOUTcontains:'."\r\n");
echo($stdout);
echo('---------------------------------'."\r\n".'STDERR contains:'."\r\n");
echo($stderr);
?>
Aside:
The line
// call your process
$process = proc_open('"C:\Program Files\TortoiseSVN\bin\svn.exe" update "c:\wamp\www\project"',
$descriptorspec,
$pipes);
could also be escaped like this
// call your process
$process = proc_open("\"C:\\Program Files\\TortoiseSVN\\bin\\svn.exe\" update \"c:\\wamp\\www\\project\"",
$descriptorspec,
$pipes);
which might or might not solve some problems on some systems that have hickups with the single brackets (') and spaces () in the notation.

Terminating proc_open after x Seconds

I am using pdftk to merge pdf files. Occasionaly a user uploads a ill formed pdf and it hangs the process returning no errors and consuming all the server resources. To prevent this i am looking at implementing the process call through proc_open and wish to set a time limit for the process to run and terminate the process if it exceeds the time limit.
Below is an example of the function that I am using to merge the pdf files if I set
stream_set_blocking($process, 0);
it returns an error:
stream_set_blocking(): supplied resource is not a valid stream resource
I presume something in this function is malformed and hope someone will be able to point me in the right direction... The function currently isn't returning any errors however does not terminate after 30 seconds as required
protected function pdf_merge($documents,$output_file,$time = 30){
$end = time() + $time;
$cmd = sprintf('/usr/local/bin/pdftk %s cat output %s', $documents, $output_file);
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("file","./error.log","a")
);
$process = proc_open($cmd, $descriptorspec, $pipes);
if (is_resource($process)) {
stream_set_blocking($pipes[1], 0);
while (!feof($pipes[1]) && (time() < $end)) {
fwrite($pipes[0], stream_get_contents($pipes[0]));
fclose($pipes[0]);
$pdf_content = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$return_value = proc_close($process);
return $return_value;
}
error_log('file is taking too long... kill process');
proc_terminate();
}
}
Perhaps I'm off base here, does most of this code run?
fwrite($pipes[0], stream_get_contents($pipes[0]));
Looks like you are trying to write to the pipe whatever you can read from the pipe...
Also, you may want to check with get_proc_status() as the command may have completed by the time you try to set the blocking...

Proc_open() c++/python

I'm trying to make a call for a c++ / python file with proc_open (bi-directional support needed).
After doing some on-line research I found created this code: (I first tried it with c++, after failure I tried python as well)
PHP:
<?php
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("file", "error-output.txt", "a")
);
$process = proc_open('new.exe', $descriptorspec, $pipes);
$input = 20;
$exp = 2;
if (is_resource($process)) {
print fgets($pipes[1]);
fwrite($pipes[0], $input);
print fgets($pipes[1]);
fwrite($pipes[0], $exp);
print fgets($pipes[1]);
fclose($pipes[1]);
fclose($pipes[0]);
$return_value = proc_close($process);
echo "command returned $return_value\n";
} else {
echo "No resource availeble";
}
?>
C++:
#include <iostream>
using namespace std;
int main () {
// Get variables from php
cout << "input" << endl;
cin << input
cout << "exponent" << endl;
cin << exp
// Process variables
int answer = input + exp;
// Return variables
cout << answer;
// End c++ script
return 0;
}
Python:
print 'enter input'
inp = raw_input()
print 'enter exponent'
exp = raw_input()
ant = inp + exp
print ant
But sadly enough it kept failing with the same error: file is not recognized as internal or external command, program or batch file.
Some extra information:
I used Wamp with PHP 5.3.0
The return value I get from proc_close() = 1
There are two problems in you code (at least for running your Python script). First, you're not flushing your Python output to it's STDOUT, so it never reaches PHP. This causes fgetc() to block infinitely. It's a simple fix, just add some flush() calls:
#!/usr/bin/env python
import sys
print 'enter input'
sys.stdout.flush()
inp = raw_input()
print 'enter exponent'
sys.stdout.flush()
exp = raw_input()
ant = inp + exp
print ant
sys.stdout.flush()
Then, in your PHP code you are not sending any newlines when you write to the Python script STDIN. So, Python's raw_input() waits indefinitely for a newline. Again, an easy fix. Just add "\n" to the fwrite() calls:
#!/usr/bin/php
<?php
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("file", "error-output.txt", "a")
);
$process = proc_open('/path/to/python/script.py', $descriptorspec, $pipes);
$input = 20;
$exp = 2;
if (is_resource($process)) {
print fgets($pipes[1]);
fwrite($pipes[0], $input . "\n");
print fgets($pipes[1]);
fwrite($pipes[0], $exp . "\n");
print fgets($pipes[1]);
fclose($pipes[1]);
fclose($pipes[0]);
$return_value = proc_close($process);
echo "command returned $return_value\n";
} else {
echo "No resource availeble";
}
And with those changes, I can make your code work as expected:
$ ./procopen.php
enter input
enter exponent
202
command returned 0
You're misunderstanding what proc_open() does. It opens a process like you would from the command line, e.g. (in Unix) diff file1.txt file2.txt. proc_open() does not run an executable.
According to the page I think you got your code from, http://php.net/manual/en/function.proc-open.php, to execute an external program you would use exec(). You can use this (provided the executable is in the right directory):
<?php
echo exec('someprogram.exe');
?>
Note: I am not certain that this will work with a Windows executable.
This is assuming that someprogram.exe is a compiled executable made from the C++ source you posted. If you wanted to run a Python program from PHP, first of all good luck using Windows, but you would want to use proc_open() to call python somescript.py, just like you would do from the command line.
Specify the absolute path of the executable file:
$process = proc_open('/path/to/new.exe', $descriptorspec, $pipes);
I can get PHP to talk to Perl with proc_open by calling the PHP script below via command line:
#!/usr/bin/php -q
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("file", "error.log", "a")
);
$process = proc_open('/path/to/procopen.pl ' . $argv[1],
$descriptorspec, $pipes);
if (is_resource($process)) {
// print pipe output
echo stream_get_contents($pipes[1]);
// close pipe
fclose($pipes[1]);
// close process
proc_close($process);
}
Here's my Perl script which is in same directory as the PHP script above:
#!/usr/bin/perl
print #ARGV;
But I can't get the PHP to run when calling your Python script. The command line just stalls forever. Why is this?

Categories