每当加载网页时,我都会调用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传递参数(通过web访问脚本)时,您需要做的是使用查询字符串并通过$_GET superglobal:访问它们
转到http://yourdomain.example/path/to/script.php?argument1=arg1&argument2=arg2
和访问:
<?php
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
?>
如果你想让脚本运行,而不管你从哪里调用它(命令行或浏览器),你会想要以下内容:
正如Cthulhu在评论中指出的那样,测试在哪个环境中执行的最直接的方法是使用PHP_SAPI常量。我已经相应地更新了代码:
<?php
if (PHP_SAPI === 'cli') {
$argument1 = $argv[1];
$argument2 = $argv[2];
}
else {
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
}
?>
$argv[0]; // the script name
$argv[1]; // the first parameter
$argv[2]; // the second parameter
如果你想运行所有的脚本,不管你从哪里调用它(命令行或浏览器),你会想要如下内容:
<?php
if ($_GET) {
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
} else {
$argument1 = $argv[1];
$argument2 = $argv[2];
}
?>
从命令行chmod 755 /var/www/webroot/index.php
调用并使用
/usr/bin/php /var/www/webroot/index.php arg1 arg2
要从浏览器调用,请使用
http://www.mydomain.example/index.php?argument1=arg1&argument2=arg2