简体   繁体   English

如何从命令行将变量传递给php

[英]how to pass variables to php from command line

I have a website on my computer on my localhost called testsite. 我在本地主机上的计算机上有一个名为testsite的网站。 Its on my apache localhost 它在我的Apache localhost上

so i can access a page http://localhost/testsite/index.php?p=763 from my browser. 这样我就可以从浏览器访问http://localhost/testsite/index.php?p=763页面。

index.php includes others php files. index.php包括其他php文件。 The index.php calls back and forth from many other php files in the folder. index.php从文件夹中的许多其他php文件来回调用。

so i went into the folder testsite and gave the command php index.php ?p=763 所以我进入了文件夹testsite并给了命令php index.php ?p=763

but it only shows the result of index.php but not with ?p=763 variable 但它只显示index.php的结果,而不显示?p=763变量

Also i want to know when i run php index.php how to list all the php files it goes through (since there are various functions called from other files). 我也想知道当我运行php index.php如何列出它经历的所有php文件(因为从其他文件调用了各种函数)。

You could add the following at the beginning of your PHP script: 您可以在PHP脚本的开头添加以下内容:

if (isset($argv[1]) && $argv[1][0] == '?') {
    parse_str(substr($argv[1], 1), $_GET);
}

It will automatically parse the argument that contains the query parameters and store them in the $_GET variable (thus making it as they came through a browser request). 它将自动解析包含查询参数的参数,并将其存储在$ _GET变量中(因此在它们通过浏览器请求时变为有效)。

Still, I wouldn't suggest relying on this approach. 不过,我不建议依靠这种方法。 You should change your application so that it will handle command line arguments properly. 您应该更改您的应用程序,以便它可以正确处理命令行参数。

To see all files that were included you should use the get_included_files function at the end of your script: 要查看其中包含的所有文件,应在脚本末尾使用get_included_files函数:

print_r(get_included_files());

$_GET is only valid for page accessed using your browser. $ _GET仅对使用浏览器访问的页面有效。 From console, inspect $argv. 从控制台,检查$ argv。 See https://stackoverflow.com/a/9612273/1349128 参见https://stackoverflow.com/a/9612273/1349128

If you do want to run a script on CLI that is designed for a web request you can cheat by setting the $_POST and $_GET variables manually from argv 如果确实要在为Web请求设计的CLI上运行脚本,则可以通过从argv手动设置$_POST$_GET变量来作弊

See this post: http://edmondscommerce.github.io/php/running-php-scripts-on-cli-and-faking-a-web-request.html 看到这篇文章: http : //edmondscommerce.github.io/php/running-php-scripts-on-cli-and-faking-a-web-request.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM