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

我需要通过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');

结果如下:

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

%targetFolder%应该返回servers

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

使用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
本文链接:https://www.f2er.com/3160665.html

大家都在问