putenv()无法为父命令行设置环境变量

时间:2019-11-05 09:54:59

标签: php batch-file cmd command-line-interface

我需要通过php设置一些环境变量,并从Windows cmd访问它们。从cmd中,我用call php\php.exe install.php 0调用php,然后install.php将设置一些环境变量。当install.php的执行完成时,我尝试从父cmd获取这些变量。但是cmd无法获得这些值。

这是我的install.php

<?php
$config = json_decode(file_get_contents('tmp/config.json'), true);
foreach ($config[$argv[1]] as $segment=>$details){
    putenv("targetFolder=$segment");
    putenv("targetLink=$details[link]");
}
echo getenv('targetFolder');

结果如下:

cmd output

%targetFolder%应该返回servers

1 个答案:

答案 0 :(得分:1)

使用setenv,您可以设置当前进程的变量,而cmd.exe是另一父变量。您cannot无需更改即可更改父进程的环境。您可能应该重写脚本,以将必要的set ENV=VALUE行放入某个临时批处理文件中,然后call

<?php
$config = json_decode(file_get_contents('tmp/config.json'), true);
$tmpBatch = fopen('tmp/setenv.bat', 'w');
foreach ($config[$argv[1]] as $segment=>$details){
    fwrite($tmpBatch, "set targetFolder=$segment");
    fwrite($tmpBatch, "set targetLink=$details[link]");
}
fclose($tmpBatch);

然后

php\php.exe install.php
call tmp\setenv.bat