[英]php - pass variables to windows .bat script?
我需要從PHP運行.bat腳本。 .bat腳本需要包含PHP變量的文件名。 我將如何在PHP中執行此操作?
謝謝!
使用fopen()
, fwrite()
和fclose()
創建.bat文件,然后使用shell_exec()
執行該文件。 看這里:
fopen: http : //us3.php.net/manual/en/function.fopen.php
fwrite: http : //us3.php.net/manual/en/function.fwrite.php
fclose: http : //us3.php.net/manual/en/function.fclose.php
shell_exec: http : //php.net/manual/en/function.shell-exec.php
================================================== ==============================
編輯:或者,如果始終傳遞相同數量的php變量且它們是標量,則可以只創建一個接受命令行參數的.bat文件,然后在shell_exec
傳遞標量變量。
要擴展Jonathan的答案,您不必使用PHP執行批處理文件。 您也可以僅使用PHP生成配置批處理文件。 然后,您可以在批處理文件中調用它以訪問所需的所有變量。 這非常靈活,將變量保存在單獨的批處理文件中可保持主代碼的整潔。
為了說明,您將需要三個文件:
batch.bat
您的主要批處理文件 setup.php
配置生成器 config.bat
配置批處理文件(由setup.php
創建) 首先,我們將創建setup.php
腳本,該腳本將生成config.bat
文件。 它可能看起來像這樣:
// Create a list of all variable names we want
// to use in the bat file, with their values.
// Note that these can come from anywhere - from
// a database, other files, remote API calls, etc.
$batVariables = array(
'InfoFile' => 'info.txt',
'TrackListing' => 'tracklist.txt',
'AuthorBio' => 'author.txt',
'MainTrack' => 'audio.mp3'
);
// create the code for the configuration
// batch file.
$batCode =
'@echo off'.PHP_EOL.
':: AUTOMATICALLY GENERATED FILE, DO NOT EDIT'.PHP_EOL.
PHP_EOL;
// add all variables
foreach($batVariables as $varName => $value)
{
$batCode .= 'set '.$varName.'='.$value.PHP_EOL;
}
// save the configuration file
file_put_contents('config.bat', $batCode);
這將生成一個如下所示的批處理文件:
@echo off
:: AUTOMATICALLY GENERATED FILE, DO NOT EDIT
set InfoFile=info.txt
set TrackListing=tracklist.txt
set AuthorBio=author.txt
set MainTrack=audio.mp3
接下來,將這兩行添加到批處理文件中(您必須確保可以在PATH系統變量中訪問php可執行文件):
:: Generate the configuration batch file
php setup.php
:: Load the configuration with all variables
call config.bat
每次使用主批處理文件時,都會生成新的配置。
通過使用call
命令加載config.bat
,變量將直接在主批處理文件的范圍內可用。 這意味着您可以像往常一樣開始使用它們,例如:
echo Using the information file %InfoFile%.
除此之外,您可能希望添加一些錯誤檢查,以防無法生成配置文件。 一種簡單的方法是確保文件存在:
IF EXIST "config.bat" (
call "config.bat"
) ELSE (
echo The configuration file does not exist.
echo.
pause
exit
)
將變量從一種編程語言傳遞到另一種? 在指定的語言支持參數之前,沒有(如果有的話)使用它(按參數傳遞變量)
如果您的bat文件僅使用文件名和一些基本參數,則只需在shell_exec()中填充適當的參數即可。
如果批處理文件為foo.bat且包含以下內容,則批處理文件命令行參數將引用%1%2等。
notepad.exe %1
您可以foo.bat textfile.txt
調用foo.bat textfile.txt
。
要從php運行它,您可以將命令行構造為字符串,然后使用它調用shell_exec
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.