I have a strange situation with a very simple batch file which I want to run from PHP, and get the exit code of this.
If I run the batch script from cmd.exe
, echo %errorleve%
will return the correct exit code, in this case 12
.
From PHP script, exit code is 0
.
my_batch.bat file
@ECHO OFF
if "1"=="1" (
if "1"=="1" (
echo quitting
exit /B 12
)
echo anything
)
my_test.php
<?php
exec('my_batch.bat',$result,$exitcode);
echo $result[0];
echo '<br />';
echo $exitcode;
Output from cmd.exe
D:\tools\xampp\htdocs\test>my_batch.bat
quitting
D:\tools\xampp\htdocs\test>echo %errorlevel%
12
D:\tools\xampp\htdocs\test>
Output oh php:
quitting
0
Thank you for your support
EDIT 1
verry strange, if I change the code with this version, all works OK
my_batch.bat file
@ECHO OFF
if "1"=="1" (
if "1"=="1" (
echo quitting
SET MYERROR=12
GOTO:END
)
echo anything
)
:END
echo finished ... ERRORLEVEL "%MYERROR%"
exit /b %MYERROR%
There is a strange anomaly which occurs in batch file when additional commands exist in any level of parenthesis the exit /b
is within.
Per your example, the exit /b 12
is the last command in parenthesis level 2 but not the last command in parenthesis level 1.
In order for the batch file to exit completely and respond with the exit
code you may turn the if
statement into an if/else
to segregate the commands from each other like so.
if "1"=="1" (
if "1"=="1" (
echo quitting
exit /b 12
) else (
echo anything
)
)