处理argc和argv

时间:2012-09-29 16:13:18

标签: php

我编写的代码如下:

<?php
array_shift($argv);
$taskid=$argv[0];
$file1=file_get_contents($argv[1]);
$file2=fopen($argv[2],"w");
echo $taskid."\n".$file1."\n".$file2."\n";
?>

我执行此程序为php myfile.php 1 1.txt 2.txt 其中1是taskid,1.txt是输入文件,2.txt是输出文件。 我想以这样的方式修改这个程序,即使我没有传递任何像php myfile.php应该运行的参数,它也会运行。我想为此设置一个if条件。我使用if(*argv<=1)和if(argc == NULL)等条件,但它们都没有工作。

我需要一个完美的条件来检查是否没有传递参数然后我的程序应该显示用户友好的消息。

有人能帮帮我吗?

2 个答案:

答案 0 :(得分:5)

if ($argc !== 4) {
  // show message 

答案 1 :(得分:2)

试试这个:

<?php
array_shift($argv);

if (empty($argv) || count($argv) != 3) {
  echo "Incorrect number of arguments\n";
}
else {
  $taskid = $argv[0];
  $file1 = file_get_contents($argv[1]);
  $file2 = fopen($argv[2],"w");
  echo $taskid . "\n" . $file1 . "\n" . $file2 . "\n";
}
相关问题