


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_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:
/**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:
$a = exec("dir", $out, $status);
print_r($a);
print_r($out);
print_r($status);
?>
system example:
$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】
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:
++++++++++++++++++++++++++++++++++++++++
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]
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:
++++++++++++++++++++++++++++++++++++++++
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
Use Notepad to write down your command and save it as a batch file, (suffix .bat).
Use winexec function to run this batch process
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;

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
