简体   繁体   中英

How do I prompt for input using PHP-CLI and have the input available as a variable?

I am looking to make a small PHP-CLI tool that will tell me if a date that I input, is a weekend day. I currently have the following script, which achieves some of this goal:

<?php
function isWeekend($date) {
return (date('N', strtotime($date)) >= 6);
}
var_dump(isWeekend('2014-10-29')); 
?>

It currently works well (outputs true or false), but I must update the source each time I want to test a date. It would be easier if I could prompt for date (user input), and then use that input to calculate the date, preferably without using HTML elements, as I am currently running the script via the CLI.

Has anyone else managed to achieve what I was looking to do? I don't need validation, as its a tool that only I will use, and I will be sure to use the correct date structure each time I use it.

when run from the command propmpt

php scriptname.php 2014-10-29 secondarg

the user input will be contained in

$argv[1]

$argv[2] //secondarg etc

of course,

strtotime($argv[1]);

will return false on failure

You can try with:

<?php
fwrite(STDOUT, "Enter the date\n");
$date = fgets(STDIN);      
$isWeekend = (date('N', strtotime($date)) >= 6);
fwrite(STDOUT, "Response: $isWeekend");  
exit(0); 
?>

This is what i am getting:

C:\xampp\php>php test.php
Enter the date
2014-11-30
Response: 1
C:\xampp\php>php test.php
Enter the date
2014-12-01
Response:
C:\xampp\php>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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