Reputation: 3293
I use WAMP and ever since I have learned PHP, I have been running my php scripts by going on the webpage itself to see the output. For example, to see the output on a script called script.php, I go on localhost/script.php.
Is there a better way to do this? I mean, in Java there's Eclipse and you can just click the green button and it'll run the code for you and see immediate output. Is there something like this for PHP?
Upvotes: 1
Views: 81
Reputation: 1554
It is possible to run PHP scripts from the command line without a web server. To do this add the following logic to your script:
if (defined('STDIN')) {
if (isset($argv)){
// handle your command line arguments here with getopt
}
}
// GET request parameter definitions //
else {
// handle your URL parameters (via GET or POST requests) here
}
When the script is run from the command line with the PHP interpreter
php myfile.php -s --longflag <argument>
STDIN is defined and you can handle command line switches, flags, and arguments with getopt in the if block.
The script reaches the else block when you access it by URL on a web server. The PHP code that you currently have can be placed in that block.
Here's an example from one of my projects that demonstrates how to handle the URL parameters as short or long command line options:
// Command line parameter definitions //
if (defined('STDIN')) {
// check whether arguments were passed, if not there is no need to attempt to check the array
if (isset($argv)){
$shortopts = "c:";
$longopts = array(
"xrt",
"xrp",
"user:",
);
$params = getopt($shortopts, $longopts);
if (isset($params['c'])){
if ($params['c'] > 0 && $params['c'] <= 200)
$count = $params['c']; //assign to the count variable
}
if (isset($params['xrt'])){
$include_retweets = false;
}
if (isset($params['xrp'])){
$exclude_replies = true;
}
if (isset($params['user'])){
$screen_name = $params['user'];
}
}
}
// Web server URL parameter definitions //
else {
// c = tweet count ( possible range 1 - 200 tweets, else default = 25)
if (isset($_GET["c"])){
if ($_GET["c"] > 0 && $_GET["c"] <= 200){
$count = $_GET["c"];
}
}
// xrt = exclude retweets from the timeline ( possible values: 1=true, else false)
if (isset($_GET["xrt"])){
if ($_GET["xrt"] == 1){
$include_retweets = false;
}
}
// xrp = exclude replies from the timeline (possible values: 1=true, else false)
if (isset($_GET["xrp"])){
if ($_GET["xrp"] == 1){
$exclude_replies = true;
}
}
// user = Twitter screen name for the user timeline that the user is requesting (default = their own, possible values = any other Twitter user name)
if (isset($_GET["user"])){
$screen_name = $_GET["user"];
}
} // end else block
I find this to be helpful for testing. Hope it helps.
Upvotes: 2