【问题标题】:putenv() can not set environment variable for parent command lineputenv() 不能为父命令行设置环境变量
【发布时间】:2019-11-05 09:54:59
【问题描述】:

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

结果如下:

%targetFolder% 应该返回 servers

【问题讨论】:

  • Call 用于同一脚本中的其他批处理文件或标签,不用于第三方可执行文件。请删除它。

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


【解决方案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

【讨论】:

    猜你喜欢
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 2014-09-02
    • 1970-01-01
    • 2014-06-04
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多