当通过 exec()
从 PHP 调用时,我无法让 wget
工作。
代码是:
exec('wget -b --timeout=300 --no-check-certificate -O c:\wgetlog.txt http://localhost/project/someparam/somevalue > c:\wgetout.txt ')
被调用的 URL 是一个基于 Zend Framework 的项目中的操作,该项目操作 MySQL 数据库中的一些数据。
执行上述时,只会创建“c:\wgetout.txt”,并且是空的。
设置如下:
- Windows 7
- XAMPP
- PHP 版本 5.3.5
- 从 here 获取最新版本
- PHP
safe_mode
已关闭
wget 安装在“C:\Program Files (x86)\GnuWin32\bin”中,并将其添加到 Windows PATH 变量中。
我知道 wget 设置正在运行,因为在运行上述 exec 参数时(如回显)
wget -b --timeout=300 --no-check-certificate -O c:\\wgetlog.txt http://localhost/project/someparam/somevalue > c:\\wgetout.txt
在命令提示符下,它运行良好,我在数据库中得到了预期的结果,并且创建了文件“C:\wgetlog.txt”和“C:\wgetout.txt”,后者包含 wget 的输出(进程 ID 等)。
后期编辑:
在Crontab的建议下成功了,使用绝对路径调用wget
,并用双引号括起来。
使用 WSH COM 对象而不是普通的 exec()
来运行它。
此外,在 Windows 上,如果输出未指向某处,则 -b
参数不起作用。由于我对输出不是特别感兴趣,所以我将其定向到 > NUL 2>&1
(这也包括错误)。
我很快制作了这个函数来帮助我在 Windows 机器上测试我的项目并让 wget
工作,所以在这里,以防有人发现它有用:
public function execWget($URL, $intTimeout = 30, $blnInBackground = true) {
if (preg_match("/Win/i", PHP_OS)) {
$runCommand = '"C:\Program Files (x86)\GnuWin32\bin\wget" ' . ($blnInBackground?'-b ':'') . '--timeout=' . (int)$intTimeout . ' --no-check-certificate ' . $URL . ($blnInBackground?' > NUL 2>&1':'');
$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run($runCommand, 7, false);
} else {
$runCommand = 'wget ' . ($blnInBackground?'-b ':'') . '--timeout=' . (int)$intTimeout . ' --no-check-certificate ' . ($blnInBackground?'-O /dev/null ':'') . $URL . ($blnInBackground?' > /dev/null 2>&1':'');
exec($runCommand);
}
}
请注意,它是为我自己的设置定制的(wget
的绝对路径),它仅用于测试目的(仅使用Windows机器进行测试,实际生产机器运行Linux),操作系统检查方法可能不是最好的等。
最佳答案
尝试使用到 wget
的绝对路径- 它可能不在您脚本的路径中。为避免使用绝对路径,您可以尝试添加 putenv("PATH=<whatever-paths-you-need-colon-delimited>");
在您访问 wget
之前在您的脚本中.另一种方法是直接修改正在运行您的网络服务器的任何用户的 PATH 环境变量(因此无论哪个用户运行 PHP 解释器)。
关于php - Windows 上的 WGET 通过 PHP exec() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9889099/