Home Backend Development PHP Tutorial Execute C/C++ applications through the Web in PHP_PHP Tutorial

Execute C/C++ applications through the Web in PHP_PHP Tutorial

Jul 13, 2016 pm 05:19 PM
c++ linux php unix web one learn app implement Introduction pass

1. Introduction
 
If you know something about Unix/Linux, you should know that most of them come with C and C++ compilers, which are GCC and G++ respectively. Unix uses these compilers in many places such as program installation and Make. Using some console commands, C++ and PHP, I will show you how to generate a complete C++ program example that can be executed in a PHP program and get the corresponding output results. I will first generate the C++ program code, compile it, and then discuss how we will execute this program by using the PHP function passthru. In a sense, this article provides us with a way to access general programs through Web pages.
 
In order to better understand this article, you should have a unix/Linux server running apache and the latest version of php. At the same time, you should also master C++ and unix console commands. Of course, some PHP programming experience is also required.
 
 2. Write a C++ program
 
For example, we can write a simple C++ program that can also receive parameters through the command line, and name it Sampleapp. Then we can Pass him three different parameters in the following way:
 
Sampleapp?Parameter one?Parameter two?Parameter three
 
The function of this program is to output the parameters passed to him The number and the value of each parameter, then we can use the PHP script program to execute the compiled C++ program.
 
Use your favorite text editor to create a new file named Sampleapp.cpp, and enter the following code into this file:

#include <iostream.h> <code>  #include <iostream.h><br>   <br>   int main(int argc, char* argv[])<br>   {<br>   cout << endl << "You passed " << argc-1 << " arguement"<BR>  << (argc-1 == 1 ? "" : "s") << "." << endl;<BR>   <BR>   cout << (argc-1 == 1 ? "This" : "These")<BR>  << " arguement" << (argc-1 == 1 ? "" : "s") << " "<BR>  << (argc-1 == 1 ? "is" : "are") << ": " << endl << endl;<BR>   <BR>   for(int i = 1; i < argc; i++)<BR>   cout << "[" << i << "] " << argv[i] << endl;<BR>   <BR>   return 0;<BR>   } 
  int main(int argc, char* argv[])
  {
  cout << endl << "You passed " << argc-1 << " argument"  cout << endl << "You passed " << argc-1 << " arguement"<BR>  << (argc-1 == 1 ? "" : "s") << "." << endl;; << (argc-1 == 1 ? "" : "s") << "." << endl;
 
cout << ( argc-1 == 1 ? "This" : "These")
 << " argumentment" << (argc-1 == 1 ? "" : "s") << " "
 << (argc-1 == 1 ? "is" : "are") << ": " << endl << endl;
    cout << (argc-1 == 1 ? "This" : "These")<BR>  << " arguement" << (argc-1 == 1 ? "" : "s") << " "<BR>  << (argc-1 == 1 ? "is" : "are") << ": " << endl << endl;  for(int i = 1; i < argc; i++)

cout << "[" << i << "] " << argv[i] << endl;

Return 0; } This C++ program contains the entry point of the program: main(). The main() function takes two parameters: argc (parameters passed in from the command line) number) and argv (an array of character pointers containing the actual values ​​of the parameters passed). These two parameters can be automatically captured by the C++ compiler.   cout << endl << "You passed " << argc-1 << " argumentment"</font> << (argc-1 == 1 ? "" : "s") << "." << endl;; 
  This sentence means to get the number of parameters passed in from the execution command line. The character pointer array Argv is retrieved starting from 0. It contains at least one actual value (that is, the path and name of this program). This value is automatically appended by the C++ compiler. The conditional operator "?" is used to determine whether there is more than one parameter passed in from the command line. For example, if two parameters are passed in from the command line, our program will output the following information: <🎜> <🎜>  You passed 2 arguments.<🎜> <🎜> cout << (argc-1 = = 1 ? "This" : "These")<🎜> << " argumentation" << (argc-1 == 1 ? "" : "s") << " "<🎜> &lt ;< (argc-1 == 1 ? "is" : "are") << ": " << endl << endl;<🎜><🎜>This news has a total of <🎜>3<🎜> pages, currently on page <🎜>1<🎜> <🎜>1<🎜> 2 3 <🎜>


Next, we also use conditional operators to output another sentence. But remember, even if we don't pass in any parameters from the program execution command line, the argv[] parameter of the main function contains a value. Similarly, if we pass two parameters to the program from the command line, the program will output the following information:
 
  These arguments are:
 
 for(int i = 1; i < argc; i++)<CODE>  for(int i = 1; i < argc; i++)<BR>   cout << "[" << i << "] " << argv[i] << endl; cout << "[" << i << "] " << argv[i] << endl; 
Finally, the main function outputs each parameter passed in from the command line one by one. It uses a simple for(;;) loop statement. This function can output the parameter values ​​one by one according to the number of parameters. If we pass two parameters "first" and second" to the program, the result of the for loop output is as follows:
 
  [1] ?first
  [2] ?second
 
  The above is about A brief description of this C++ program. Its function is very simple, which is to display the parameters passed in from the command line on the output screen using the cout function.
 
Next, we will compile this .cpp file. If you are using Under the windows platform, you need to telnet to the server you are using. Here, we use the G++ compiler provided on most Unix machines to compile this source file. But to make sure that your machine has G++ installed, You can enter the following command: which g++. If G++ is installed, the Unix shell will display the full path of G++. If it is not installed, it will prompt you saying "command couldn't be found". You can download it here. G++.
 
Enter the following G++ command in the directory where the source file is located:

  g++ -c sampleapp.cpp.
With this command, we compile the .cpp file into a target file containing machine code . Through the ls?a command, you can find that a new file sampleapp.o appears in this directory. This is the result of the .cpp source file being compiled into machine code, but what we ultimately want is an executable file. We also need to enter the following G++ command:
, it does not have any suffix
   g++ sampleapp.cpp ?o sampleapp Next we can check the results of program execution, if the following command:



We can see the following execution results:
  sampleapp one -two /three You passed 3 arguments.

These arguments are:

[1] one
[2] ? two
  [3] /three
 
Now that the executable C++ program has been generated, we will generate a PHP tutorial program that can access this program through a web browser.


This news has a total of
3

pages, currently on page

2

1 2 3


3. Generate PHP script program

In order to call our C++ program through the Internet, we need to generate A PHP script program. This PHP script will have a Form so that the user can enter parameters that can be passed to the Sampleapp program. The code of the PHP script is too long so I won’t list it all here. If necessary, you can download it from the address below. (Php code)
 

  if(@$submit)<CODE>  if(@$submit)<BR>   {<BR>   <BR>   }<BR>   else<BR>   {<BR>   }  {
 
  }
  else
  {
  }
First, the script program checks to see if the variable $submit has a value. The value of this variable $submit is passed after the Form form behind the program is submitted. It defaults to a null value. The function of the @ symbol is to ignore the relevant error message when the value of the variable $submit does not exist.
   if($args == "")<BR>   echo "<h1>You didnt enter any arguments.</h1>";<br>   else<br>   {<br>   echo "<h1>SampleApp Result</h1>";<br>   $command = "/htdocs/sampleapp " . escapeshellcmd($args);<br>   <br>   passthru($command);<br>   } Since the variable $submit is empty by default, the code in else{} is initially executed, which simply displays a Form on the browser. The action attribute of the Form is set to the variable $PHP_SELF, that is, this page is returned after the form is submitted. At the same time, the Form form contains a text input bar, which is used to allow users to enter command line parameters to be passed to the C++ program. Form is as shown below:
 
Once we enter the execution command and submit the form, the variable $submit (that is, the name of the button Go) gets a value, so that the PHP textbook will execute the code between if{}.
 
 if($args == "")<br>  echo "<h1>You didn't enter any arguments.</h1>";<code>  $command = "/htdocs/sampleapp " . escapeshellcmd($args);  else
  {
Echo "

SampleApp Result

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

passthru($command);
}  
  The variable $args is automatically generated, and its value is the value passed from the text input bar in the Form form. If no information is entered, the program will simply tell the user that no value was entered.
 
If the user enters any non-empty information, the program will pass the value of the text field, the variable $args, to the C++ program. The following code is the execution command for executing a C++ program:
 

The function eacapeshellcmd is used as a security check tool to filter calls such as ",", "" and "", etc. special characters. This prevents some users from trying to enter certain characters to invoke internal system commands.

   You can see that we defined the full path of the program sampleapp. In this example, the program file is located in the /htdocs directory. You can make corresponding modifications according to the directory where your own program is located.   passthru($command); Finally, we use the PHP function passthru to execute the command contained in the variable $command and output the original execution result to the browser. On my server, the HTML page that returns the results is as follows:    wBefore the end of this article, I would like to talk about a few problems that may be encountered. First of all, when you execute the sampleapp.php tutorial program, if you do not see any output information from the program, it may be that the safe mode is turned on. If so, the system will not allow PHP scripts to execute system internal programs. For information on how to turn off safe mode, please visit the web page http://www.php.net/manual/en/features.safe-mode.php on
http://www.bkjia.com/PHPjc/532648.htmlwww.bkjia.com
truehttp: //www.bkjia.com/PHPjc/532648.htmlTechArticle1. Introduction If you know something about Unix/Linux, you should know that most of them come with C and C++ compilers are GCC and G++ respectively. Unix is ​​used in many places such as program installation and Make...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

Describe the purpose and usage of the ... (splat) operator in PHP function arguments and array unpacking. Describe the purpose and usage of the ... (splat) operator in PHP function arguments and array unpacking. Apr 06, 2025 am 12:07 AM

The... (splat) operator in PHP is used to unpack function parameters and arrays, improving code simplicity and efficiency. 1) Function parameter unpacking: Pass the array element as a parameter to the function. 2) Array unpacking: Unpack an array into another array or as a function parameter.

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

How can you prevent a class from being extended or a method from being overridden in PHP? (final keyword) How can you prevent a class from being extended or a method from being overridden in PHP? (final keyword) Apr 08, 2025 am 12:03 AM

In PHP, the final keyword is used to prevent classes from being inherited and methods being overwritten. 1) When marking the class as final, the class cannot be inherited. 2) When marking the method as final, the method cannot be rewritten by the subclass. Using final keywords ensures the stability and security of your code.

Unable to log in to mysql as root Unable to log in to mysql as root Apr 08, 2025 pm 04:54 PM

The main reasons why you cannot log in to MySQL as root are permission problems, configuration file errors, password inconsistent, socket file problems, or firewall interception. The solution includes: check whether the bind-address parameter in the configuration file is configured correctly. Check whether the root user permissions have been modified or deleted and reset. Verify that the password is accurate, including case and special characters. Check socket file permission settings and paths. Check that the firewall blocks connections to the MySQL server.

C language conditional compilation: a detailed guide for beginners to practical applications C language conditional compilation: a detailed guide for beginners to practical applications Apr 04, 2025 am 10:48 AM

C language conditional compilation is a mechanism for selectively compiling code blocks based on compile-time conditions. The introductory methods include: using #if and #else directives to select code blocks based on conditions. Commonly used conditional expressions include STDC, _WIN32 and linux. Practical case: Print different messages according to the operating system. Use different data types according to the number of digits of the system. Different header files are supported according to the compiler. Conditional compilation enhances the portability and flexibility of the code, making it adaptable to compiler, operating system, and CPU architecture changes.

Explain strict types (declare(strict_types=1);) in PHP. Explain strict types (declare(strict_types=1);) in PHP. Apr 07, 2025 am 12:05 AM

Strict types in PHP are enabled by adding declare(strict_types=1); at the top of the file. 1) It forces type checking of function parameters and return values ​​to prevent implicit type conversion. 2) Using strict types can improve the reliability and predictability of the code, reduce bugs, and improve maintainability and readability.

See all articles