search
HomeBackend DevelopmentPHP TutorialHow to start Windows applications, execute bat batch processing, and execute cmd commands in PHP (detailed explanation of exec and system functions), detailed explanation of exec function_PHP tutorial

How to start Windows applications, execute bat batch processing, and execute cmd commands in PHP (detailed explanation of exec and system functions), detailed explanation of exec function

Exec or system can call cmd commands

Go directly to the code:

Copy code The code is as follows:

/**Open the windows calculator*/
exec('start C:WindowsSystem32calc.exe');

/**After php generates the windows batch file, then execute the batch file*/
$filename = 't.bat';
$somecontent = 'C:
';
$somecontent .= 'cd "C:/Program Files/MySQL-Front"';
$somecontent .= '
start MySQL-Front.exe';
if (!$handle = fopen($filename, 'w')) {
echo "Cannot open file $filename";
exit;
}

/**First we need to make sure the file exists and is writable*/
if (is_writable($filename)) {

/**That is where $somecontent will be written when we use fwrite()
Write $somecontent to the file we opened.*/
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file $filename";
exit;
}
echo "Successfully written $somecontent to file $filename";
fclose($handle);
} else {
echo "File $filename is not writable";
}
exec($filename);
?>

There is a remaining problem, which is the exec() call. PHP will continue to execute until you close the started application. This will cause the PHP execution to time out. I don’t know how to solve this problem. I hope experts will pass by here and leave answers! I will solve it in the future and will update it here!

The following comes from information

================================================== ==

PHP’s built-in functions exec and system can call system commands (shell commands), and of course there are functions such as passthru and escapeshellcmd.

In many cases, using PHP's exec, system and other functions to call system commands can help us complete our work better and faster.

Note: If you want to use these two functions, the safe mode in php.ini must be turned off, otherwise php will not allow calling system commands for security reasons.

First take a look at the explanation of these two functions in the PHP manual:

exec --- Execute external program

Syntax: string exec ( string command [, array &output [, int &return_var]] )

Description:
exec() executes the given command command, but it does not output anything. It simply returns the last line from the result of the command. If you need to execute a command and get all the information from the command, you can use it. passthru() function.
If the argument array is given, the specified array will be filled with each line output by the command. Note: If the array already contains some elements, exec() will append it to the end of the array. If you don't want to To append elements to this function, you can call unset() before passing the array to exec().
If the parameters array and return_var are given, the status command returned by the execution will be written to this variable.

Note: If you allow data from user input to be passed to this function, then you should use escapeshellcmd() to ensure that the user cannot trick the system into executing arbitrary commands.

Note: If you use this function to start a program and want to leave it while executing in the background, you must make sure that the output of the program is redirected to a file or some output data. stream, otherwise PHP will hang until the program execution ends.

system --- Execute external programs and display output

Syntax: string system ( string command [, int &return_var] )

Description:

system() executes the given command command and outputs the result. If the parameter return_var is given, the status code of the executed command will be written to this variable.

Note: If you allow data from user input to be passed to this function, then you should use escapeshellcmd() to ensure that the user cannot trick the system into executing arbitrary commands.

Note: If you use this function to start a program and want to leave it while executing in the background, you must make sure that the output of the program is redirected to a file or some output data. stream, otherwise PHP will hang until the program execution ends.
If PHP is running as a server module, system() will try to automatically clear the web server's output buffer after each line of output.

Returns the last line of the command if successful, false if failed.

If you need to execute a command and get all the data from the command, you can use the passthru() function.

These two are used to call system shell commands,

Differences:

Exec can return all execution results to the $output function (array). $status is the execution status. 0 means success and 1 means failure

systerm does not need to provide the $output function. It returns the result directly. Similarly, $return_var is the execution status code. 0 is success and 1 is failure

exec example:

Copy code The code is as follows:

$a = exec("dir", $out, $status);
print_r($a);
print_r($out);
print_r($status);
?>

system example:
Copy code The code is as follows:

$a = system("dir", $status);
print_r($a);
print_r($status);
?>

The above instructions may seem a bit confusing, but you will understand after running two examples!

【system】

Copy code The code is as follows:

set_time_limit(0);
define('ROOT_PATH', dirname(__FILE__));

include ROOT_PATH . '/include/global.func.php';

$cmdTest = 'ps -ef | grep magent';

$lastLine = system($cmdTest, $retVal);

write_log('$lastLine');
write_log($lastLine);

write_log('$retVal');
write_log($retVal);
?>

Output:

Copy code The code is as follows:

++++++++++++++++++++++++++++++++++++++++
2014-10-15 16:28:52
$lastLine
++++++++++++++++++++++++++++++++++++++++
2014-10-15 16:28:52
root 5375 5373 0 16:28 pts/1 00:00:00 grep magent
++++++++++++++++++++++++++++++++++++++++
2014-10-15 16:28:52
$retVal
++++++++++++++++++++++++++++++++++++++++
2014-10-15 16:28:52
0

[exec]

Copy code The code is as follows:

set_time_limit(0);
define('ROOT_PATH', dirname(__FILE__));

include ROOT_PATH . '/include/global.func.php';

$cmdTest = 'ps -ef | grep magent';

$lastLine = exec($cmdTest, $output, $retVal);

write_log('$lastLine');
write_log($lastLine);

write_log('$output');
write_log($output);

write_log('$retVal');
write_log($retVal);
?>

Output:

Copy code The code is as follows:

++++++++++++++++++++++++++++++++++++++++
2014-10-15 16:25:00
$lastLine
++++++++++++++++++++++++++++++++++++++++
2014-10-15 16:25:00
root 5360 5358 0 16:25 pts/1 00:00:00 grep magent
++++++++++++++++++++++++++++++++++++++++
2014-10-15 16:25:00
$output
++++++++++++++++++++++++++++++++++++++++
2014-10-15 16:25:00
Array
(
[0] => root 2838 1 0 15:39 ? 00:00:00 magent -u root -n 51200 -l 192.168.137.100 -p 12001 -s 192.168.137.100:11211 -b 192.1 68.137.100:11212
[1] => root 5358 5356 0 16:25 pts/1 00:00:00 sh -c ps -ef | grep magent
[2] => root 5360 5358 0 16:25 pts/1 00:00:00 grep magent
)

++++++++++++++++++++++++++++++++++++++++
2014-10-15 16:25:00
$retVal
++++++++++++++++++++++++++++++++++++++++
2014-10-15 16:25:00
0

Conclusion:

If you need detailed output results, use exec()! I usually use exec() to execute external commands!

Reference:

http://php.net/manual/zh/function.system.php
http://php.net/manual/zh/function.exec.php

How to execute cmd command in c++ without system function

Use Notepad to write down your command and save it as a batch file, (suffix .bat).
Use winexec function to run this batch process

How to execute cmd command or bat processing in php - Technical Q&A

The function uses these two exec();system(); If it doesn’t work, it may be that you wrote the command wrong. $str =null;exec(\"dir c:\",$str);Usage as above;

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/897017.htmlTechArticlePHP methods to start windows applications, execute bat batch processing, and execute cmd commands (detailed explanation of exec and system functions), Detailed explanation of exec function. Either exec or system can call cmd command directly...
Statement
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
PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use