Nic*_*ick 137 php parameters
每当网页加载时我都会调用PHP脚本.但是,有一个PHP脚本需要运行的参数(我通常在测试脚本时通过命令行).
每次在页面加载时运行脚本时,如何传递此参数?
Jas*_*son 228
大概你在命令行中传递参数如下:
php /path/to/wwwpublic/path/to/script.php arg1 arg2
Run Code Online (Sandbox Code Playgroud)
...然后在脚本中访问它们:
<?php
// $argv[0] is '/path/to/wwwpublic/path/to/script.php'
$argument1 = $argv[1];
$argument2 = $argv[2];
?>
Run Code Online (Sandbox Code Playgroud)
通过HTTP传递参数(通过Web访问脚本)时需要做的是使用查询字符串并通过$ _GET超全局访问它们:
转到http://yourdomain.com/path/to/script.php?argument1=arg1&argument2=arg2
...和访问:
<?php
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
?>
Run Code Online (Sandbox Code Playgroud)
如果您希望脚本运行,无论您从哪里(命令行或浏览器)调用它,您都需要以下内容:
编辑:正如Cthulhu在评论中所指出的,测试您正在执行哪个环境的最直接方法是使用PHP_SAPI常量.我相应地更新了代码:
<?php
if (PHP_SAPI === 'cli') {
$argument1 = $argv[1];
$argument2 = $argv[2];
}
else {
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
}
?>
Run Code Online (Sandbox Code Playgroud)
小智 16
$argv[0]; // the script name
$argv[1]; // the first parameter
$argv[2]; // the second parameter
Run Code Online (Sandbox Code Playgroud)
如果您想要运行所有脚本,无论您从哪里(命令行或浏览器)调用它,您都需要以下内容:
<?php
if ($_GET) {
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
} else {
$argument1 = $argv[1];
$argument2 = $argv[2];
}
?>
Run Code Online (Sandbox Code Playgroud)
从命令行调用chmod 755 /var/www/webroot/index.php
并使用
/usr/bin/php /var/www/webroot/index.php arg1 arg2
Run Code Online (Sandbox Code Playgroud)
要从浏览器调用,请使用
http://www.mydomain.com/index.php?argument1=arg1&argument2=arg2
Run Code Online (Sandbox Code Playgroud)