Passing output from C++ to PHP - php

I am creating a PHP file to pass values to a c++ .exe which will then calculate an output and return that output. However, I cannot seem to get the output from the .exe back into the PHP file.
PHP Code:
$path = 'C:enter code here\Users\sumit.exe';
$handle = popen($path,'w');
$write = fwrite($handle,"37");
pclose($handle);
C++ Code:
#include "stdafx.h"
#include <iostream>
using namespace std;
// Declaation of Input Variables:
int main()
{
int num;
cin>> num;
std::cout<<num+5;
return 0;
}

I'd advise neither system nor popen but proc_open command: php.net
Call it like
$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("pipe", "w") // stderr, also a pipe the child will write to
);
proc_open('C:enter code here\Users\sumit.exe', $descriptorspec, $pipes);
After that you'll have $pipes filled with handles to send data to program ([0]) and recieve data from program ([1]). Also you will have [2] which you can use to get stderr from the program (or just close if you don't use stderr).
Don't forget to close process handle with proc_close() and pipe handles with fclose(). Note that your program will not know the output is complete before you close $pipes[0] handle or write some whitespace character. I advise closing the pipe.
Using command line arguments in system() or popen() is valid, though if you intend to send large amounts of data and/or raw data, you will have trouble with command line length limits and with escaping special chars.

In your C++ code I am not seeing anything for passing variables in you need
int main(int argc, char* argv[])
instead of
int main()
Remember argc is the count of variables and it includes the path to the file, so your arguments begin at 1 with each argv being a c-string of that argument. If you need a decimal atof is your friend or atoi for an integer.
Then you are using popen. The PHP documentation says that it can be only used for reading or writting. It is not bi-directional. You want to use proc_open to have bi-directional support.
Anyways, This is how I would write your C++ code:
#include "stdafx.h"
#include <iostream>
// Declaation of Input Variables:
int main(int arc, char* argv[])
{
int num;
num = atoi(argv[1]);
std::cout<<num+5;
return 0;
}
Note: I removed using namespace std because I noticed you were still trying to use the namespace in the main function (i.e. std::cout) and it better to keep it out of a global namespace.

you are writing into exe file, you should pass your argument like
system("C:enter code here\Users\sumit.exe 37");

Related

Communication between PHP and C++

I want to communicate PHP and C++ code.
I need to pass a big JSON between them.
The problem is that I am currently using "passthru", but for some reason I do not know, the C ++ code does not receive the entire parameter, but is cut in 528 characters when the JSON is 3156.
By performing tests, I have been able to verify that the "passthru" command supports as many characters as 3156. But I do not know if there is a maximum input parameter size in C ++.
The PHP application is as follows:
passthru('programc++.exe '.$bigJSON, $returnVal);
The C++ application:
int main(int argc, char* argv[]){
char *json = argv[1];
}
Is there any way to fix the problem? I have read about PHP extensions and IPC protocols, but the problem is that I have to do a multiplatform program (I must have a version for Windows, another for Linux and for Mac). And I think that using PHP extensions and IPC protocols (as far as I could read) complicates things quite a bit.
Solution:
The solution is use "proc_open" and use the pipe stdin and stdout. In my case, I use the library rapidjson. I add double quotes in PHP in order to rapidJSON works and process the JSON.
PHP:
$exe_command = 'program.exe';
$descriptorspec = array(
0 => array("pipe", "r"), // stdin
1 => array("pipe", "w"), // stdout -> we use this
2 => array("pipe", "w") // stderr
);
$process = proc_open($exe_command, $descriptorspec, $pipes);
$returnValue = null;
if (is_resource($process)){
fwrite($pipes[0], $bigJSON);
fclose($pipes[0]);
$returnValue = stream_get_contents($pipes[1]);
fclose($pipes[1]);
}
C++:
int main(int argc, char* argv[]){
std::string json;
std::getline (std::cin, json);
cout << json << endl; // The JSON
}

PHP: pipe and passthru to mix and match external linux program (with STDIN and STDOUT) as components

I am a PHP beginner. I want to invoke an external Unix command, pipe some stuff into it (e.g., string and files), and have the result appear in my output buffer (the browser).
Consider the following:
echo '<h1>stuff for my browser output window</h1>';
$fnmphp= '/tmp/someinputfile';
$sendtoprogram = "myheader: $fnmphp\n\n".get_file_contents($fnmphp);
popen2outputbuf("unixprogram < $sendtoprogram");
echo '<p>done</p>';
An even better solution would let PHP write myheader (into Unix program), then pipe the file $fnmphp (into Unix program); and the output of unixprogram would immediately go to my browser output buffer.
I don't think PHP uses stdout, so that my Unix program STDOUT output would make it into the browser. Otherwise, this would happen to default if I used system(). I can only think of solutions that require writing tempfiles.
I think I am standing on the line here (German idiom; wires crossed)--- this probably has an obvious solution.
update:
here is the entirely inelegant but pretty precise solution that I want to replace:
function pipe2eqb( $text ) {
$whatever= '/tmp/whatever-'.time().'-'.$_SESSION['uid'];
$inf = "$whatever.in";
$outf= "$whatever.out";
assert(!file_exists($inf));
assert(!file_exists($outf));
file_put_contents($inf, $text);
assert(file_exists($inf));
system("unixprog < $inf > $outf");
$fo= file_get_contents($outf);
unlink($infilename);
unlink($outfilename);
return $fo;
}
It is easy to replace either the input or the output, but I want to replace both. I will post a solution when I figure it out.
the best to do this is the proc_open family of functions
<?php
$descriptorspec = array(
0 => array("pipe", "r"), // stdin
1 => array("pipe", "w"), // stdout
2 => array("pipe", "w") // stderr
);
$cwd = NULL;//'/tmp';
$env = NULL;//array();
$cmd='unixprog ';
$process = proc_open($cmd, $descriptorspec, $pipes, $cwd, $env);
assert(false!==$process);
now, to give arguments to unixprog, do like
$cmd='unixprog --arg1='.escapeshellarg($arg1).' --arg2='.escapeshellarg($arg2);
to talk to the program's stdin, do like
assert(strlen($stdinmessage)===fwrite($pipes[0],$stdinmessage));
to read from the process's stdout, do like
$stdout=file_get_contents($pipes[$1])
to read from the process's stderr, do like
$stderr=file_get_contents($pipes[$2])
to check if the program has finished, do like
$status=proc_get_status($process);
if($status['running']){echo 'child process is still running.';}
to check the return code of the process when it has finished,
echo 'return code from child process: '.$status['exitcode'];
to wait for the child process to finish, you CAN do
while(proc_get_status($process)['running']){sleep(1);}
this is a quick and easy way to do it, but it is not optimal. tl;dr: it may be slow or waste cpu. long version:
there is some nigh-optimal event-driven way to do this, but im not sure how to do it. imagine having to run a program 10 times, but the program execute in 100 milliseconds. this code would use 10 seconds! while optimal code would use only 1 second. you can use usleep() for microseconds, but its still not optimal, imagine if you're checking every 100 microseconds, but the program use 10 seconds to execute: you would waste cpu, checking the status 100,000 times, while optimal code would only check it once.. im sure there is a fancy way to let php sleep until the process finishes with some callback/signal, perhaps with stream_select , but i've yet to solve it. (if anybody have the solution, please let me know!)
-- read more at http://php.net/manual/en/book.exec.php

Runnig process with proc_open

I have one php script and I want to call a process writting in C from the PHP scrit. There are many ways to do it(system,exec...), but Ï chosse the function proc_open. With this I can open a pipe in stdin and stdout with the C process, but I don´t know how to get the data from stdin in the C process. Can anyone help me with a example?.Thank you
In C, stdin, stdout and stderr are constant FILE pointers defined in <stdio.h>. For example, to read from stdin:
#include <stdio.h>
int main() {
int ch = fgetc(stdin); //read 1 character from stdin
fputc(ch, stdout); //dump to stdout
//...
return 0;
}

How to pass the content of a variable trough an external command in php?

I have a variable that contains a long string. (specifically it contains a few kilobytes of javascript-code)
I want to pass this string trough an external command, in this case a javascript-compressor, and capture the output of the external command (the compressed javascript) in php, assigning it to a variable.
I'm aware that there's classes for compressing javascript in php, but this is merely one example of a general problem.
originally we used:
$newvar = passthru("echo $oldvar | compressor");
This works for small strings, but is insecure. (if oldvar contains characters with special meaning to the shell, then anything could happen)
Escaping with escapeshellarg fixes that, but the solution breaks for longer strings, because of OS-limitations on maximum allowable argument-length.
I tried using popen("command" "w") and writing to the command - this works, but the output from the command silently disappears into the void.
Conceptually, I just want to do the equivalent of:
$newvar = external_command($oldvar);
Using the proc_open-function you can get handles to both stdout and stdin of the process and thus write your data to it and read the result.
Using rumpels suggestion, I was able to device the following solution which seems to work well. Posting it here for the benefit of anyone else interested in the question.
public static function extFilter($command, $content){
$fds = 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("pipe", "w") // stderr is a pipe that the child will write to
);
$process = proc_open($command, $fds, $pipes, NULL, NULL);
if (is_resource($process)) {
fwrite($pipes[0], $content);
fclose($pipes[0]);
$stdout = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[2]);
$return_value = proc_close($process);
// Do whatever you want to do with $stderr and the commands exit-code.
} else {
// Do whatever you want to do if the command fails to start
}
return $stdout;
}
There may be deadlock-issues: if the data you send is larger than the combined sizes of the pipes, then the external command will block, waiting for someone to read from it's stdout, while php is blocked, waiting for stdin to be read from to make room for more input.
Possibly PHP takes care of this issue somehow, but it's worth testing out if you plan to send (or receive) more data than fits in the pipes.

Redirecting I/O in PHP

<?php
fclose(STDIN);
fclose(STDOUT);
fclose(STDERR);
$STDIN = fopen("/tmp/some-named-pipe", "r");
$STDOUT = fopen("/tmp/foo.out", "wb");
$STDERR = fopen("/tmp/foo.err", "wb");
echo "Hello, World!"; // goes to /tmp/foo.out, implied STDOUT
fscanf($STDIN, "%s\n", $top_secret); // explicit $STDIN, cant use STDIN
?>
Why is it that the redirection to the new STDOUT works implicitly, yet the redirection from the new STDIN must happen explicitly?
The original STDIN, STDOUT and STDERR are system constants in PHP. They are populated with the file descriptor resources of the standard input, output and error upon initialization of PHP.
The php.net documentation describes the following regarding resources in constants:
The value of the constant; only scalar and null values are allowed.
Scalar values are integer, float, string or boolean values. It is
possible to define resource constants, however it is not recommended
and may cause unpredictable behavior.
When fclose(STDOUT) is called, the file descriptor resource is closed and detached from the STDOUT constant. Contrary to the default behavior of constants, the STDOUT constant is changed.
When a string is echo'ed like echo "Hello, World!", PHP will not use the STDOUT constant, but it will query the current "standard out" file descriptor in real-time from the operating system. Moreover, the STDOUT constant itself is rendered unusable once it is fclose'd. Even a statement like fwrite(STDOUT, "hello") will not work.
When a new file descriptor is configured for the standard output, this new file descriptor is conveniently put in $STDOUT. Note that this is a variable and not a constant. It is by definition not possible to redefine a constant in PHP, and the system constant STDOUT is no exception here. There is currently no way to reassign the new file descriptor to the STDOUT constant.
Ultimately, to make this work more intuitively, the PHP team should consider making convenience functions to reassign these file descriptors or at least make the system constants operate more like "magic constants" in a sense that they auto evaluate to the actual file descriptors.
This is an example for redirecting stdout several times.
The close of STDOUT works for the first time, but for the next time
the close of $STDOUT is needed.
<?php
# Redirecting 10 times ...
# Need to close 'STDOUT' & '$STDOUT', otherwise the 2nd time
# the redirecting fails.
for ( $i = 1; $i <= 10; $i++ )
{
$sLogName = sprintf("reopen_%02d.log", $i);
echo "Redirecting to '" . $sLogName . "' ...\n";
fclose(STDOUT);
fclose($STDOUT); # Needed for reopening after the first time.
$STDOUT = fopen($sLogName, "w");
echo "Now logging in file '" . $sLogName . "' ...\n";
}
?>
This is happening only in UNIX-like systems (linux, etc), because when you open a file unix use the minor file descriptor, so in a process STDIN, STDOUT and STDERR are always 0,1 and 2.
When you do this:
fclose(STDIN);
fclose(STDOUT);
fclose(STDERR);
$STDIN = fopen("/tmp/some-named-pipe", "r");
$STDOUT = fopen("/tmp/foo.out", "wb");
$STDERR = fopen("/tmp/foo.err", "wb");
you are closing STDIN (0), STDOUT (1) and STDERR(2), so when you open your files in the same order they get 0,1 and 2 as file descriptor. If you run the same code on windows it will not work.
What I see first when reading your snippet is that you first try to close the constants of STDIN, STDOUT etc. But then use variables which have the same name to open files; therefore the values you're working with are completely different, $STDIN is not the same as STDIN. You might be able to redefine STDIN using the define function, but I'm not sure and unable to check without a computer atm..

Categories