Quantcast

Executing A C++ Application Over The Internet With PHP

Get the WebProNews Newsletter:
[ Technology]

Page 1: Introduction
If you’ve ever had any exposure to Unix/Linux, then you would know that it has both C and C++ compilers built into it: GCC and G++ respectively. Unix uses these compilers extensively during program installations, makes, etc. Using a couple of console commands, some C++ and some PHP, I will show you how to create a totally integrated C++ sample application, which can be executed (and have its output captured) from PHP.

I will create the C++ application, compile it, and then talk about how we can execute that application via PHP using the passthru function. In a sense, this provides access to our application over the Internet.

To get the most from this article, you should have a Unix/Linux server setup running Apache and the latest version of PHP. A good grasp of C++ (standard ANSI-compatible C++), the Unix console, and some PHP experience are also required.

Page 2: Creating the C++ application
For this example, I will create a simple C++ application that will accept arguments via the command line. If we have an application named “sampleapp”, for example, then we can pass it three command-line arguments like this:

sampleapp -firstarg –secondarg -thirdarg

The application will output the number of arguments sent to it, as well as the values of each of these arguments. We will use a PHP script to execute the compiled C++ application via the passthru function.

Using your favorite text editor, create a new text file named sampleapp.cpp. Enter the following code into sampleapp.cpp:

#include <iostream.h>

int main(int argc, char* argv[])
{
  cout << endl << “You passed ” <<
argc-1 << ” arguement” << (argc-1   ==
1 ? “” : “s”) << “.” << endl;
  cout << (argc-1 == 1 ? “This” : “These”) <<
” arguement” << (argc-1 ==   1 ? “” : “s”) <<
” ” << (argc-1 == 1 ? “is” : “are”) << “: ” <<
endl << endl;
  for(int i = 1; i < argc; i++) cout << “["
<< i << "] ” << argv[i] << endl;
  return 0;
}

Our C++ file contains the programs entry point, main. The main function accepts two arguments: argc (the number of arguments passed to the application from the command line), and argv (an array of character-pointers, containing the actual values of the command line arguments). These two arguments are automatically captured and passed-in by the C++ compiler.

  cout << endl << “You passed ” <<
argc-1 << ” arguement” << (argc-1   ==
1 ? “” : “s”) << “.” << endl;

The main function starts by outputting the number of arguments that were passed to the application from the command line. The argv pointer-to-character array is indexed from zero onwards, and will always contain at least one value (the full path and name of our application), which is automatically added by the C++ compiler. We use the conditional operator, “?”, to deduce whether or not there was more than one argument passed in from the command line. If, for example, we passed two arguments from the command line, then our application would output the following line:

You passed 2 arguments.

  cout << (argc-1 == 1 ? “This” : “These”) <<
” arguement” << (argc-1 ==   1 ? “” : “s”) <<”
” << (argc-1 == 1 ? “is” : “are”) << “: ” <<
endl << endl;

Next, we use the same conditional operator to output another sentence. Remember, that the argv[] argument of the main function will contain one value even if we don’t pass any in from the command line. Again, if we passed two arguments from the command line, then our application would output the following line:

These arguments are:

  for(int i = 1; i << argc; i++)
  cout << "[" <<i << "] " << argv[i]
<< endl;

Lastly, the main function outputs each of the command line arguments that are passed in. It uses a simple for(;;) loop, which keeps count of the number of arguments which have been outputted so far. If we passed in two arguments, "-firstArg", and "-secondArg", then the output of the for loop would look like this:

[1] –firstArg
[2] –secondArg

That’s our C++ application explained. It simply accepts arguments from the command line, and then displays these arguments on the screen, using the cout function.

You’ll now need to upload the sampleapp.cpp file to your Unix web server using some sort of FTP program. I recommend CuteFTP. Make sure you upload your .cpp file into a non-publicly accessible folder.

To compile the sampleapp.cpp file, we need to connect to our web server using telnet. We will use the G++ compiler (which compiles standard-ANSI C++ files on Unix), which is readily available on all Unix systems. Just to make sure you have G++ installed, enter the following command at the Unix prompt:

which g++

If you have G++ installed, then the Unix shell will display the full path to its executable. If not, it will tell you that the command couldn’t be found. If this is the case, then you can download G++ here.

Change into the directory where you uploaded the sampleapp.cpp file into. Use the "cd" command to do this. The "cd" (change directory) command is the same on Unix as it is on windows, except you use forward slashes to change into a directory, not black slashes: cd /myfiles

This would put me into the "myfiles" directory of my root folder (assuming I have access to the "myfiles" directory and that it exists).

Next, we need to use the G++ compiler to compile our .cpp file into an object file containing machine code. Use the G++ command like this:

g++ -c sampleapp.cpp

If you use the "ls –a" command to view the contents of the current directory, then you will see that the G++ compiler has created a new file, "sampleapp.o". This file contains the machine code version of our .cpp file. We actually want to create an executable file from this object file. To do this, we use the following command:

g++ sampleapp.cpp –o sampleapp

This creates a new executable file named "sampleapp". Keep in mind that Unix executables don’t contain any file extension.

To test the "sampleapp" executable, enter the following command at the Unix shell: sampleapp one -two /three

The following output will be shown on our screen:

You passed 3 arguments. These arguments are:

[1] one
[2] –two
[3] /three

Now that our executable file ready to go, let’s create a PHP script that we will use to access it from our web browser.

Page 3: Creating the PHP script
To call our compiled C++ application over the Internet, we will create a PHP script. This PHP script will display a HTML form into which we can enter arguments to pass to the “sampleapp” executable. The entire code for the PHP script is a bit too long to list, so you can download it as part of the support material for this article, from the last page.

  if(@$submit)
  {
  }
  else
  {
  }

Firstly, our script checks to see whether the $submit variable contains a value. The $submit variable is passed from the form submitted at the bottom of the script, and by default, will be empty. The @ symbol stops PHP from spitting an error if the $submit variable doesn’t exist.

Because the $submit variable is empty by default, the code between the “else” braces is executed. This simply outputs a HTML form to the web browser. The “action” attribute of the form is set to the $PHP_SELF variable, which will submit the form back to itself. The form contains one text field, into which we will enter the command-line arguments to pass to our C++ application. The form looks like this:

Once we enter some arguments and submit the form, the $submit variable (which is the name of the “Go” button) will contain a value. This will cause our PHP script to execute the code between the “if” braces:

if($args == “”)
echo “<h1>You didn’t enter any
arguments.</h1>”;
else
{
echo “<h1>SampleApp Result</h1>”;
$command = “/htdocs/sampleapp ” .
escapeshellcmd($args);
passthru($command);
}

The $args variable is automatically created and given the value of the text field in our HTML form. If no arguments were entered, we simply tell the user that they didn’t enter any:

On the other hand, if they entered at least one character into the text field, then we pass that text fields value, $args, to our C++ application. Because we will be executing our C++ application, we create the command that we will actually execute (more on this in a minute):

$command = “/htdocs/sampleapp ” . escapeshellcmd($args);

The escapeshellcmd function is used as a safety measure, and escapes characters such as ‘, ” and with ’, ” and . This prevents users from entering any arguments that could trigger internal Unix commands.

If we entered “1 –two /three” into the text field of our HTML form, for example, then our $command variable would contain:

/htdocs/sampleapp 1 –two /three

You can see that we are specifying the full path to our sampleapp file. In this example, mine is located in the “/htdocs” directory. You should change this to match the full path to the sampleapp file on your server.

passthru($command);

Lastly, we use the passthru PHP function, which will execute our $command variable as an external Unix program and pass the raw output back to our web browser. On my server, the resultant HTML page looks like this:

I just want to mention a couple of things before I wrap this article up. Firstly, if you don’t receive any output from your program when you run the sampleapp.php script on your web server, safe mode may be on. This will stop execution of external programs from within a PHP script. Visit http://www.php.net/manual/en/features.safe-mode.php for details on turning safe mode off.

Also, on some Unix systems, the PHP function passthru doesn’t send the output from the external program back to the web browser. If this is the case for you, try using the system function instead.

Page 4: Conclusion
As you can see from the example in this article, the Unix operating system is very powerful, and PHP was designed from scratch to allow developers to execute external programs as independent threads, via a script. The example described in this article is very elementary. With a bit of work, however, you could create a C++ application that would update a MySQL database, run another system command, or do something with the files/directory structure of your web server. Always make sure that your security settings are correct, and never give open-access to your internal applications via any sort of script.

If you’re after more information on anything mentioned in this article, take a look at the links and books shown below.

For more great programming articles, please visit http://www.devarticles.com. If you have an opinion or question about this article, then please post it at the devArticles developer forum, which is located at http://www.devarticles.com/forum

DevArticles (http://www.devarticles.com) went “live-to-air” in November of 2001. Starting out as just a one man show ran by me from my bedroom, DevArticles quickly became one of the most popular developer sites on the ‘net. Most people attribute it to the way that we write our articles, but I’d also like to think that it’s our strong sense of community that has helped make us what we are today.

Executing A C++ Application Over The Internet With PHP
Comments Off
About DevArticles
DevArticles (http://www.devarticles.com) went "live-to-air" in November of 2001. Starting out as just a one man show ran by me from my bedroom, DevArticles quickly became one of the most popular developer sites on the 'net. Most people attribute it to the way that we write our articles, but I'd also like to think that it's our strong sense of community that has helped make us what we are today. WebProNews Writer
Top Rated White Papers and Resources

Comments are closed.

  • Join for Access to Our Exclusive Web Tools
  • Sidebar Top
  • Sidebar Middle
  • Sign Up For The Free Newsletter
  • Sidebar Bottom