Dhanya Santhosh
Dhanya Santhosh

Reputation: 101

How to call an executable file from a PHP script

I want to run a PHP script which calls an executable cpp file on a remote server.

I have tried like below:

1.Created a cpp file

// function example
#include <iostream>
using namespace std;

int addition (int a, int b)
{
    int r;
    r=a+b;
    return r;
}

int main ()
{
    int z;
    z = addition (5,3);
    cout << "The result is " << z;
    return z;
} 

Generated its .exe file and put it in server's folder(test.exe)

Step2 : Created a php scripts which call exe file using 'shell_exec'

<?php 
if (function_exists('shell_exec')){
    echo "Enabled";
} else {
    echo "Disabled";
}
$file = 'test.exe';
if (!file_exists($file)) echo 'File does not exists';
$out= shell_exec($file);
//exec($file, $out);
echo 'ouput is:: ' .$out;?>

Also, I've put this PHP file on a remote server and tried to call the PHP script in the browser. But it shows error Warning: shell_exec() [function.shell-exec]: Unable to execute 'test.exe'. I want to echo "ouput is:: 8".

Please help to verify.

Upvotes: 0

Views: 3742

Answers (1)

marc_s
marc_s

Reputation: 455

Use:

exec("./test.exe", $out);

Note that $out will hold the output.
remember thatshell_exec returns all of the output stream as a string, but exec returns the last line of the output.

Upvotes: 1

Related Questions