每当网页加载时我都会调用 PHP 脚本。但是,PHP 脚本需要运行一个参数(我在测试脚本时通常通过命令行传递该参数)。
每次加载页面时运行脚本时如何传递此参数?
假设您在命令行上传递参数,如下所示:
php /path/to/wwwpublic/path/to/script.php arg1 arg2
...然后在脚本中访问它们:
<?php
// $argv[0] is '/path/to/wwwpublic/path/to/script.php'
$argument1 = $argv[1];
$argument2 = $argv[2];
?>
通过 HTTP 传递参数(通过网络访问脚本)时,您需要做的是使用查询字符串并通过 $_GET 超全局访问它们:
Go to http://yourdomain.example/path/to/script.php?argument1=arg1&argument2=arg2
...和访问:
<?php
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
?>
如果您希望脚本无论从何处调用(命令行或浏览器)都运行,您将需要如下所示的内容:
正如 Cthulhu 在评论中指出的,测试您正在执行的环境的最直接方法是使用PHP_SAPI http://php.net/manual/en/reserved.constants.php#constant.php-sapi持续的。我相应地更新了代码:
<?php
if (PHP_SAPI === 'cli') {
$argument1 = $argv[1];
$argument2 = $argv[2];
}
else {
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
}
?>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)