Santhosh
Santhosh

Reputation: 11778

how to pass variables to php from command line

I have a website on my computer on my localhost called testsite. Its on my apache localhost

so i can access a page http://localhost/testsite/index.php?p=763 from my browser.

index.php includes others php files. The index.php calls back and forth from many other php files in the folder.

so i went into the folder testsite and gave the command php index.php ?p=763

but it only shows the result of index.php but not with ?p=763 variable

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).

Upvotes: 0

Views: 1284

Answers (3)

edmondscommerce
edmondscommerce

Reputation: 2011

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

See this post: http://edmondscommerce.github.io/php/running-php-scripts-on-cli-and-faking-a-web-request.html

Upvotes: 0

Razvan
Razvan

Reputation: 2596

You could add the following at the beginning of your PHP script:

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).

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:

print_r(get_included_files());

Upvotes: 2

OK11
OK11

Reputation: 74

$_GET is only valid for page accessed using your browser. From console, inspect $argv. See https://stackoverflow.com/a/9612273/1349128

Upvotes: 1

Related Questions