C++ is the best performing programming language that was created by Bjarne Stroustrup in earlier days and the modern programming languages are finding it hard to compete with C++ even today. It is always a better idea to use multiple programming languages while building an application so that a complex task is best performed by a programming language that can handle better. However, the performance of the application also depends on the optimization of the algorithm used too. Here in this article, we will see how to execute C++ program using PHP. PHP has a powerful function that comes bundled. It's shell_exec()
. This function is capable of running a shell command through PHP. Beware of attackers though! This function could be misused on your web application and an attacker could inject malicious command in order to attack the web server. Let us say, that we have a simple C++ program that prints your name by getting your name as a command line argument. I will call this file to be say-hello.cpp.
#include using namespace std; int main(int argc, char *argv[]) { if(argc != 1) { cout << "Hello, " << argv[1] << endl; } else { cout << "Please pass me your name!" << endl; } return 0; }
The arguments argc
and argv[]
in the main()
are responsible for getting the command line arguments. The variable argc
stores the number of arguments supplied and argv
is an array of arguments that you provide while executing. You need to remember that the first index of argv
is always the file name that you are executing. Compile your C++ code by using g++. I have provided a link below to install G++ on Windows.
g++ say-hello.cpp -o say-hello.out
Run your code using the following command:
./say-hello.out CryptLife
So, the output will be:
Hello, CryptLife
I believe that you do have a working web server or a local WAMP/MAMP/XAMPP server running on your machine and PHP included in it. In your htdocs or www or public_html folder of your web server directory, create a folder for your project and we will add the above C++ output file into it (say-hello.out). Let us create an HTML form where it gets theĀ name of the visitor and submits it to a send.php file. Let us call this file as form.html.
Now let us write our send.php. It's just that simple.
This will execute run the C++ output. Learn more: Installing g++ on Windows Please share your comments below if you have any queries.