Pregunta

I have a simple hello world command line application which I a trying to execute via php but I don't know how to switch to the debug folder of the application and then run the executable. So far I have tried using popen to move the location where the terminal is, however it seems incorrect in the way I have done it and then used exec to execute the command.

Heres my PHP file:

<?php
$loc = '/Users/dave/Library/Developer/Xcode/DerivedData/HelloWorld-akuofooecqboeybtsfalcrelvfjt/Build/Products/Debug';
$argv = "./HelloWorld j";
popen($loc, 'r');
echo exec($argv);

And heres my c++ command line program:

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
    if( argc < 2 )
    { printf("Please enter a value \n");
        return -1;
    }
    std::cout << argv[1]<<"\n";
    std::cout << "Hello, World!\n";
    return 0;
}

The directory where the debug folder for this is /Users/dave/Library/Developer/Xcode/DerivedData/HelloWorld-akuofooecqboeybtsfalcrelvfjt/Build/Products/Debug and to execute this I used ./HelloWorld x (slight note how would this work if the HelloWorld application had a space?)

Everything works fine when I do run this from the terminal, so it is not a problem with the c++ file.

So can someone please tell me how can I execute this application from php?

¿Fue útil?

Solución

in php you can execute a command via system() function :

system('YOUR COMMAND - FOR EXAMPLE ./HelloWorld (in your path)');

to get the result you can put it into an variable.

$test=system("some command");
var_dump($test);

In your case:

system('PATH/HelloWorld j'); // runs your HelloWorld executable file

Another solution is using shell_exec() function. As php.net example:

$output = shell_exec('ls -lart');
echo "<pre>$output</pre>";

each one has its own advantages and disadvantages. You can read more about mentioned functions in php.net/following links:

shell_exec — Execute command via shell and return the complete output as a string

system — Execute an external program and display the output

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top