<em id="gxj5d"></em>
          <delect id="gxj5d"><ins id="gxj5d"><form id="gxj5d"></form></ins></delect>
          <dl id="gxj5d"></dl><em id="gxj5d"></em>
          <div id="gxj5d"><tr id="gxj5d"></tr></div>

          <em id="gxj5d"><ol id="gxj5d"><mark id="gxj5d"></mark></ol></em>

                <dl id="gxj5d"><ol id="gxj5d"></ol></dl><em id="gxj5d"></em>
                <em id="gxj5d"><ol id="gxj5d"></ol></em>
                <sup id="gxj5d"><menu id="gxj5d"></menu></sup>
                    <span id="gxj5d"><form id="gxj5d"><wbr id="gxj5d"></wbr></form></span><dl id="gxj5d"><ins id="gxj5d"></ins></dl>
                      <div id="gxj5d"><tr id="gxj5d"></tr></div>
                      <em id="gxj5d"></em>

                      <em id="gxj5d"><ol id="gxj5d"><thead id="gxj5d"></thead></ol></em>
                          add a note add a note

                          User Contributed Notes 54 notes

                          up
                          97
                          sep16 at psu dot edu
                          6 years ago
                          You can easily parse command line arguments into the $_GET variable by using the parse_str() function.

                          <?php

                          parse_str
                          (implode('&', array_slice($argv, 1)), $_GET);

                          ?>

                          It behaves exactly like you'd expect with cgi-php.

                          $ php -f somefile.php a=1 b[]=2 b[]=3

                          This will set $_GET['a'] to '1' and $_GET['b'] to array('2', '3').

                          Even better, instead of putting that line in every file, take advantage of PHP's auto_prepend_file directive.  Put that line in its own file and set the auto_prepend_file directive in your cli-specific php.ini like so:

                          auto_prepend_file = "/etc/php/cli-php5.3/local.prepend.php"

                          It will be automatically prepended to any PHP file run from the command line.
                          up
                          20
                          ben at slax0rnet dot com
                          15 years ago
                          Just a note for people trying to use interactive mode from the commandline.

                          The purpose of interactive mode is to parse code snippits without actually leaving php, and it works like this:

                          [[email protected] php-4.3.4]# php -a
                          Interactive mode enabled

                          <?php echo "hi!"; ?>
                          <note, here we would press CTRL-D to parse everything we've entered so far>
                          hi!
                          <?php exit(); ?>
                          <ctrl-d here again>
                          [[email protected] php-4.3.4]#

                          I noticed this somehow got ommited from the docs, hope it helps someone!
                          up
                          11
                          Kodeart
                          7 years ago
                          Check directly without calling functions:
                          <?php
                          if (PHP_SAPI === 'cli')
                          {
                            
                          // ...
                          }
                          ?>

                          You can define a constant to use it elsewhere
                          <?php
                          define
                          ('ISCLI', PHP_SAPI === 'cli');
                          ?>
                          up
                          7
                          linn at backendmedia dot com
                          15 years ago
                          For those of you who want the old CGI behaviour that changes to the actual directory of the script use:
                          chdir(dirname($_SERVER['argv'][0]));

                          at the beginning of your scripts.
                          up
                          12
                          notreallyanaddress at somerandomaddr dot com
                          9 years ago
                          If you want to be interactive with the user and accept user input, all you need to do is read from stdin. 

                          <?php
                          echo "Are you sure you want to do this?  Type 'yes' to continue: ";
                          $handle = fopen ("php://stdin","r");
                          $line = fgets($handle);
                          if(
                          trim($line) != 'yes'){
                              echo
                          "ABORTING!\n";
                              exit;
                          }
                          echo
                          "\n";
                          echo
                          "Thank you, continuing...\n";
                          ?>
                          up
                          5
                          Anonymous
                          8 years ago
                          Using CLI (on WIN at least), some INI paths are relative to the current working directory.  For example, if your error_log = "php_errors.log", then php_errors.log will be created (or appended to if already exists) in whatever directory you happen to be in at the moment if you have write access there.  Instead of having random error logs all over the place because of this behavior, you may want to set error_log to a full path, perhaps to the php.exe directory.
                          up
                          7
                          Adam, php(at)getwebspace.com
                          15 years ago
                          Ok, I've had a heck of a time with PHP > 4.3.x and whether to use CLI vs CGI. The CGI version of 4.3.2 would return (in browser):
                          ---
                          No input file specified.
                          ---

                          And the CLI version would return:
                          ---
                          500 Internal Server Error
                          ---

                          It appears that in CGI mode, PHP looks at the environment variable PATH_TRANSLATED to determine the script to execute and ignores command line. That is why in the absensce of this environment variable, you get "No input file specified." However, in CLI mode the HTTP headers are not printed. I believe this is intended behavior for both situations but creates a problem when you have a CGI wrapper that sends environment variables but passes the actual script name on the command line.

                          By modifying my CGI wrapper to create this PATH_TRANSLATED environment variable, it solved my problem, and I was able to run the CGI build of 4.3.2
                          up
                          5
                          OverFlow636 at gmail dot com
                          13 years ago
                          I needed this, you proly wont tho.
                          puts the exicution args into $_GET
                          <?php
                          if ($argv) {
                              foreach (
                          $argv as $k=>$v)
                              {
                                  if (
                          $k==0) continue;
                                 
                          $it = explode("=",$argv[$i]);
                                  if (isset(
                          $it[1])) $_GET[$it[0]] = $it[1];
                              }
                          }
                          ?>
                          up
                          6
                          eric dot brison at anakeen dot com
                          11 years ago
                          Just a variant of previous script to accept arguments with '=' also
                          <?php
                          function arguments($argv) {
                             
                          $_ARG = array();
                              foreach (
                          $argv as $arg) {
                                if (
                          ereg('--([^=]+)=(.*)',$arg,$reg)) {
                                 
                          $_ARG[$reg[1]] = $reg[2];
                                } elseif(
                          ereg('-([a-zA-Z0-9])',$arg,$reg)) {
                                     
                          $_ARG[$reg[1]] = 'true';
                                  }
                            
                              }
                            return
                          $_ARG;
                          }
                          ?>
                          $ php myscript.php --user=nobody --password=secret -p --access="host=127.0.0.1 port=456"
                          Array
                          (
                              [user] => nobody
                              [password] => secret
                              [p] => true
                              [access] => host=127.0.0.1 port=456
                          )
                          up
                          7
                          thomas dot harding at laposte dot net
                          10 years ago
                          Parsing command line: optimization is evil!

                          One thing all contributors on this page forgotten is that you can suround an argv with single or double quotes. So the join coupled together with the preg_match_all will always break that :)

                          Here is a proposal:

                          #!/usr/bin/php
                          <?php
                          print_r
                          (arguments($argv));

                          function
                          arguments ( $args )
                          {
                           
                          array_shift( $args );
                           
                          $endofoptions = false;

                           
                          $ret = array
                              (
                             
                          'commands' => array(),
                             
                          'options' => array(),
                             
                          'flags'    => array(),
                             
                          'arguments' => array(),
                              );

                            while (
                          $arg = array_shift($args) )
                            {

                             
                          // if we have reached end of options,
                              //we cast all remaining argvs as arguments
                             
                          if ($endofoptions)
                              {
                               
                          $ret['arguments'][] = $arg;
                                continue;
                              }

                             
                          // Is it a command? (prefixed with --)
                             
                          if ( substr( $arg, 0, 2 ) === '--' )
                              {

                               
                          // is it the end of options flag?
                               
                          if (!isset ($arg[3]))
                                {
                                 
                          $endofoptions = true;; // end of options;
                                 
                          continue;
                                }

                               
                          $value = "";
                               
                          $com   = substr( $arg, 2 );

                               
                          // is it the syntax '--option=argument'?
                               
                          if (strpos($com,'='))
                                  list(
                          $com,$value) = split("=",$com,2);

                               
                          // is the option not followed by another option but by arguments
                               
                          elseif (strpos($args[0],'-') !== 0)
                                {
                                  while (
                          strpos($args[0],'-') !== 0)
                                   
                          $value .= array_shift($args).' ';
                                 
                          $value = rtrim($value,' ');
                                }

                               
                          $ret['options'][$com] = !empty($value) ? $value : true;
                                continue;

                              }

                             
                          // Is it a flag or a serial of flags? (prefixed with -)
                             
                          if ( substr( $arg, 0, 1 ) === '-' )
                              {
                                for (
                          $i = 1; isset($arg[$i]) ; $i++)
                                 
                          $ret['flags'][] = $arg[$i];
                                continue;
                              }

                             
                          // finally, it is not option, nor flag, nor argument
                             
                          $ret['commands'][] = $arg;
                              continue;
                            }

                            if (!
                          count($ret['options']) && !count($ret['flags']))
                            {
                             
                          $ret['arguments'] = array_merge($ret['commands'], $ret['arguments']);
                             
                          $ret['commands'] = array();
                            }
                          return
                          $ret;
                          }

                          exit (
                          0)

                          /* vim: set expandtab tabstop=2 shiftwidth=2: */
                          ?>
                          up
                          4
                          rob
                          12 years ago
                          i use emacs in c-mode for editing.  in 4.3, starting a cli script like so:

                          #!/usr/bin/php -q /* -*- c -*- */
                          <?php

                          told emacs to drop into c
                          -mode automatically when i loaded the file for editingthe '-q' flag didn't actually do anything (in the older cgi versions, it suppressed html output when the script was run) but it caused the commented mode line to be ignored by php.

                          in 5.2, '
                          -q' has apparently been deprecated.  replace it with '--' to achieve the 4.3 invocation-with-emacs-mode-line behavior:

                          #!/usr/bin/php -- /* -*- c -*- */
                          <?php

                          don'
                          t go back to your 4.3 system and replace '-q' with '--'; it seems to cause php to hang waiting on STDIN...
                          up
                          3
                          monte at ispi dot net
                          15 years ago
                          I had a problem with the $argv values getting split up when they contained plus (+) signs. Be sure to use the CLI version, not CGI to get around it.

                          Monte
                          up
                          2
                          frankNospamwanted at. toppoint dot. de
                          4 years ago
                          Parsing commandline argument GET String without changing the PHP script (linux shell):
                          URL: index.php?a=1&b=2
                          Result: output.html

                          echo "" | php -R 'include("index.php");' -B 'parse_str($argv[1], $_GET);' 'a=1&b=2' >output.html

                          (no need to change php.ini)

                          You can put this
                            echo "" | php -R 'include("'$1'");' -B 'parse_str($argv[1], $_GET);' "$2"
                          in a bash script "php_get" to use it like this:
                            php_get index.php 'a=1&b=2' >output.html
                          or directed to text browser...
                            php_get index.php 'a=1&b=2' |w3m -T text/html
                          up
                          3
                          jeff at noSpam[] dot genhex dot net
                          16 years ago
                          You can also call the script from the command line after chmod'ing the file (ie: chmod 755 file.php).

                          On your first line of the file, enter "#!/usr/bin/php" (or to wherever your php executable is located).  If you want to suppress the PHP headers, use the line of "#!/usr/bin/php -q" for your path.
                          up
                          3
                          goalain eat gmail dont com
                          12 years ago
                          If your php script doesn't run with shebang (#!/usr/bin/php),
                          and it issues the beautifull and informative error message:
                          "Command not found."  just dos2unix yourscript.php
                          et voila.

                          If you still get the "Command not found."
                          Just try to run it as ./myscript.php , with the "./"
                          if it works - it means your current directory is not in the executable search path.

                          If your php script doesn't run with shebang (#/usr/bin/php),
                          and it issues the beautifull and informative message:
                          "Invalid null command." it's probably because the "!" is missing in the the shebang line (like what's above) or something else in that area.

                          \Alon
                          up
                          1
                          lucas dot vasconcelos at gmail dot com
                          11 years ago
                          Just another variant of previous script that group arguments doesn't starts with '-' or '--'

                          <?php
                          function arguments($argv) {
                             
                          $_ARG = array();
                              foreach (
                          $argv as $arg) {
                                if (
                          ereg('--([^=]+)=(.*)',$arg,$reg)) {
                                 
                          $_ARG[$reg[1]] = $reg[2];
                                } elseif(
                          ereg('^-([a-zA-Z0-9])',$arg,$reg)) {
                                     
                          $_ARG[$reg[1]] = 'true';
                                } else {
                                     
                          $_ARG['input'][]=$arg;
                                }
                              }
                            return
                          $_ARG;
                          }

                          print_r(arguments($argv));
                          ?>

                          $ php myscript.php --user=nobody /etc/apache2/*
                          Array
                          (
                              [input] => Array
                                  (
                                      [0] => myscript.php
                                      [1] => /etc/apache2/apache2.conf
                                      [2] => /etc/apache2/conf.d
                                      [3] => /etc/apache2/envvars
                                      [4] => /etc/apache2/httpd.conf
                                      [5] => /etc/apache2/mods-available
                                      [6] => /etc/apache2/mods-enabled
                                      [7] => /etc/apache2/ports.conf
                                      [8] => /etc/apache2/sites-available
                                      [9] => /etc/apache2/sites-enabled
                                  )

                              [user] => nobody
                          )
                          up
                          2
                          Alexander Plakidin
                          16 years ago
                          How to change current directory in PHP script to script's directory when running it from command line using PHP 4.3.0?
                          (you'll probably need to add this to older scripts when running them under PHP 4.3.0 for backwards compatibility)

                          Here's what I am using:
                          chdir(preg_replace('/\\/[^\\/]+$/',"",$PHP_SELF));

                          Note: documentation says that "PHP_SELF" is not available in command-line PHP scripts. Though, it IS available. Probably this will be changed in future version, so don't rely on this line of code...

                          Use $_SERVER['PHP_SELF'] instead of just $PHP_SELF if you have register_globals=Off
                          up
                          2
                          volkany at celiknet dot com
                          16 years ago
                          Here goes a very simple clrscr function for newbies...
                          function clrscr() { system("clear"); }
                          up
                          1
                          [email protected]
                          11 years ago
                          In 5.1.2 (and others, I assume), the -f form silently drops the first argument after the script name from $_SERVER['argv']. I'd suggest avoiding it unless you need it for a special case.
                          up
                          1
                          apmuthu at usa dot net
                          1 year ago
                          Adding a pause() function to PHP waiting for any user input returning it:

                          <?php
                          function pause() {
                             
                          $handle = fopen ("php://stdin","r");
                              do {
                          $line = fgets($handle); } while ($line == '');
                             
                          fclose($handle);
                              return
                          $line;
                          }
                          ?>
                          up
                          1
                          pyxl at jerrell dot com
                          17 years ago
                          Assuming --prefix=/usr/local/php, it's better to create a symlink from /usr/bin/php or /usr/local/bin/php to target /usr/local/php/bin/php so that it's both in your path and automatically correct every time you rebuild.  If you forgot to do that copy of the binary after a rebuild, you can do all kinds of wild goose chasing when things break.
                          up
                          2
                          stromdotcom at hotmail dot com
                          13 years ago
                          Spawning php-win.exe as a child process to handle scripting in Windows applications has a few quirks (all having to do with pipes between Windows apps and console apps).

                          To do this in C++:

                          // We will run php.exe as a child process after creating
                          // two pipes and attaching them to stdin and stdout
                          // of the child process
                          // Define sa struct such that child inherits our handles

                          SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES) };
                          sa.bInheritHandle = TRUE;
                          sa.lpSecurityDescriptor = NULL;

                          // Create the handles for our two pipes (two handles per pipe, one for each end)
                          // We will have one pipe for stdin, and one for stdout, each with a READ and WRITE end
                          HANDLE hStdoutRd, hStdoutWr, hStdinRd, hStdinWr;

                          // Now create the pipes, and make them inheritable
                          CreatePipe (&hStdoutRd, &hStdoutWr, &sa, 0))
                          SetHandleInformation(hStdoutRd, HANDLE_FLAG_INHERIT, 0);
                          CreatePipe (&hStdinRd, &hStdinWr, &sa, 0)
                          SetHandleInformation(hStdinWr, HANDLE_FLAG_INHERIT, 0);

                          // Now we have two pipes, we can create the process
                          // First, fill out the usage structs
                          STARTUPINFO si = { sizeof(STARTUPINFO) };
                          PROCESS_INFORMATION pi;
                          si.dwFlags = STARTF_USESTDHANDLES;
                          si.hStdOutput = hStdoutWr;
                          si.hStdInput  = hStdinRd;

                          // And finally, create the process
                          CreateProcess (NULL, "c:\\php\\php-win.exe", NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);

                          // Close the handles we aren't using
                          CloseHandle(hStdoutWr);
                          CloseHandle(hStdinRd);

                          // Now that we have the process running, we can start pushing PHP at it
                          WriteFile(hStdinWr, "<?php echo 'test'; ?>", 9, &dwWritten, NULL);

                          // When we're done writing to stdin, we close that pipe
                          CloseHandle(hStdinWr);

                          // Reading from stdout is only slightly more complicated
                          int i;

                          std::string processed("");
                          char buf[128];

                          while ( (ReadFile(hStdoutRd, buf, 128, &dwRead, NULL) && (dwRead != 0)) ) {
                              for (i = 0; i < dwRead; i++)
                                  processed += buf[i];
                          }   

                          // Done reading, so close this handle too
                          CloseHandle(hStdoutRd);

                          A full implementation (implemented as a C++ class) is available at http://www.stromcode.com
                          up
                          1
                          phpnotes at ssilk dot de
                          16 years ago
                          To hand over the GET-variables in interactive mode like in HTTP-Mode (e.g. your URI is myprog.html?hugo=bla&bla=hugo), you have to call

                          php myprog.html '&hugo=bla&bla=hugo'

                          (two & instead of ? and &!)

                          There just a little difference in the $ARGC, $ARGV values, but I think this is in those cases not relevant.
                          up
                          -1
                          sam marshall
                          3 months ago
                          When using the -R flag, the name of the variable containing the content of the current line (not including the LF) is $argn.

                          For example you can do this code:

                          cat file.txt | php -R 'echo $argn . "\n";'

                          This will just output each line of the input file without doing anything to it.
                          up
                          0
                          ohcc at 163 dot com
                          2 years ago
                          use " instead of ' on windows when using the cli version with -r

                          php -r "echo 1"
                          -- correct

                          php -r 'echo 1'
                            PHP Parse error:  syntax error, unexpected ''echo' (T_ENCAPSED_AND_WHITESPACE), expecting end of file in Command line code on line 1
                          up
                          1
                          obfuscated at emailaddress dot com
                          14 years ago
                          This posting is not a php-only problem, but hopefully will save someone a few hours of headaches.  Running on MacOS (although this could happen on any *nix I suppose), I was unable to get the script to execute without specifically envoking php from the command line:

                          [macg4:valencia/jobs] tim% test.php
                          ./test.php: Command not found.

                          However, it worked just fine when php was envoked on the command line:

                          [macg4:valencia/jobs] tim% php test.php
                          Well, here we are...  Now what?

                          Was file access mode set for executable?  Yup.

                          [macg4:valencia/jobs] tim% ls -l
                          total 16
                          -rwxr-xr-x  1 tim  staff   242 Feb 24 17:23 test.php

                          And you did, of course, remember to add the php command as the first line of your script, yeah?  Of course.

                          #!/usr/bin/php
                          <?php print "Well, here we are...  Now what?\n"; ?>

                          So why dudn't it work?  Well, like I said... on a Mac.... but I also occasionally edit the files on my Windows portable (i.e. when I'm travelling and don't have my trusty Mac available)...  Using, say, WordPad on Windows... and BBEdit on the Mac...

                          Aaahhh... in BBEdit check how the file is being saved!  Mac?  Unix?  or Dos?  Bingo.  It had been saved as Dos format.  Change it to Unix:

                          [macg4:valencia/jobs] tim% ./test.php
                          Well, here we are...  Now what?
                          [macg4:valencia/jobs] tim%

                          NB: If you're editing your php files on multiple platforms (i.e. Windows and Linux), make sure you double check the files are saved in a Unix format...  those \r's and \n's 'll bite cha!
                          up
                          0
                          PSIKYO at mail dot dlut dot edu dot cn
                          5 years ago
                          If you edit a php file in windows, upload and run it on linux with command line method. You may encounter a running problem probably like that:

                          [[email protected] wsdl]# ./lnxcli.php
                          Extension './lnxcli.php' not present.

                          Or you may encounter some other strange problem.
                          Care the enter key. In windows environment, enter key generate two binary characters '0D0A'. But in Linux, enter key generate just only a 'OA'.
                          I wish it can help someone if you are using windows to code php and run it as a command line program on linux.
                          up
                          0
                          james_s2010 at NOSPAM dot hotmail dot com
                          11 years ago
                          I was looking for a way to interactively get a single character response from user. Using STDIN with fread, fgets and such will only work after pressing enter. So I came up with this instead:

                          #!/usr/bin/php -q
                          <?php
                          function inKey($vals) {
                             
                          $inKey = "";
                              While(!
                          in_array($inKey,$vals)) {
                                 
                          $inKey = trim(`read -s -n1 valu;echo \$valu`);
                              }
                              return
                          $inKey;
                          }
                          function
                          echoAT($Row,$Col,$prompt="") {
                             
                          // Display prompt at specific screen coords
                             
                          echo "\033[".$Row.";".$Col."H".$prompt;
                          }
                             
                          // Display prompt at position 10,10
                             
                          echoAT(10,10,"Opt : ");

                             
                          // Define acceptable responses
                             
                          $options = array("1","2","3","4","X");

                             
                          // Get user response
                             
                          $key = inKey($options);

                             
                          // Display user response & exit
                             
                          echoAT(12,10,"Pressed : $key\n");
                          ?>

                          Hope this helps someone.
                          up
                          0
                          losbrutos at free dot fr
                          11 years ago
                          an another "another variant" :

                          <?php
                          function arguments($argv)
                          {
                           
                          $_ARG = array();
                            foreach (
                          $argv as $arg)
                            {
                              if (
                          preg_match('#^-{1,2}([a-zA-Z0-9]*)=?(.*)$#', $arg, $matches))
                              {
                               
                          $key = $matches[1];
                                switch (
                          $matches[2])
                                {
                                  case
                          '':
                                  case
                          'true':
                                   
                          $arg = true;
                                    break;
                                  case
                          'false':
                                   
                          $arg = false;
                                    break;
                                  default:
                                   
                          $arg = $matches[2];
                                }
                               
                          $_ARG[$key] = $arg;
                              }
                              else
                              {
                               
                          $_ARG['input'][] = $arg;
                              }
                            }
                            return
                          $_ARG;
                          }
                          ?>

                          $php myscript.php arg1 -arg2=val2 --arg3=arg3 -arg4 --arg5 -arg6=false

                          Array
                          (
                              [input] => Array
                                  (
                                      [0] => myscript.php
                                      [1] => arg1
                                  )

                              [arg2] => val2
                              [arg3] => arg3
                              [arg4] => true
                              [arg5] => true
                              [arg5] => false
                          )
                          up
                          0
                          djcassis at gmail
                          12 years ago
                          To display colored text when it is actually supported :
                          <?php
                          echo "\033[31m".$myvar; // red foreground
                          echo "\033[41m".$myvar; // red background
                          ?>

                          To reset these settings :
                          <?php
                          echo "\033[0m";
                          ?>

                          More fun :
                          <?php
                          echo "\033[5;30m;\033[48mWARNING !"; // black blinking text over red background
                          ?>

                          More info here : http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html
                          up
                          0
                          drewish at katherinehouse dot com
                          13 years ago
                          When you're writing one line php scripts remember that 'php://stdin' is your friend. Here's a simple program I use to format PHP code for inclusion on my blog:

                          UNIX:
                            cat test.php | php -r "print htmlentities(file_get_contents('php://stdin'));"

                          DOS/Windows:
                            type test.php | php -r "print htmlentities(file_get_contents('php://stdin'));"
                          up
                          0
                          docey
                          13 years ago
                          dunno if this is on linux the same but on windows evertime
                          you send somthing to the console screen php is waiting for
                          the console to return. therefor if you send a lot of small
                          short amounts of text, the console is starting to be using
                          more cpu-cycles then php and thus slowing the script.

                          take a look at this sheme:
                          cpu-cycle:1 ->php: print("a");
                          cpu-cycle:2 ->cmd: output("a");
                          cpu-cycle:3 ->php: print("b");
                          cpu-cycle:4 ->cmd: output("b");
                          cpu-cycle:5 ->php: print("c");
                          cpu-cycle:6 ->cmd: output("c");
                          cpu-cylce:7 ->php: print("d");
                          cpu-cycle:8 ->cmd: output("d");
                          cpu-cylce:9 ->php: print("e");
                          cpu-cycle:0 ->cmd: output("e");

                          on the screen just appears "abcde". but if you write
                          your script this way it will be far more faster:
                          cpu-cycle:1 ->php: ob_start();
                          cpu-cycle:2 ->php: print("abc");
                          cpu-cycle:3 ->php: print("de");
                          cpu-cycle:4 ->php: $data = ob_get_contents();
                          cpu-cycle:5 ->php: ob_end_clean();
                          cpu-cycle:6 ->php: print($data);
                          cpu-cycle:7 ->cmd: output("abcde");

                          now this is just a small example but if you are writing an
                          app that is outputting a lot to the console, i.e. a text
                          based screen with frequent updates, then its much better
                          to first cach all output, and output is as one big chunk of
                          text instead of one char a the time.

                          ouput buffering is ideal for this. in my script i outputted
                          almost 4000chars of info and just by caching it first, it
                          speeded up by almost 400% and dropped cpu-usage.

                          because what is being displayed doesn't matter, be it 2
                          chars or 40.0000 chars, just the call to output takes a
                          great deal of time. remeber that.

                          maybe someone can test if this is the same on unix-based
                          systems. it seems that the STDOUT stream just waits for
                          the console to report ready, before continueing execution.
                          up
                          0
                          roberto dot dimas at gmail dot com
                          13 years ago
                          One of the things I like about perl and vbscripts, is the fact that I can name a file e.g. 'test.pl' and just have to type 'test, without the .pl extension' on the windows command line and the command processor knows that it is a perl file and executes it using the perl command interpreter.

                          I did the same with the file extension .php3 (I will use php3 exclusivelly for command line php scripts, I'm doing this because my text editor VIM 6.3 already has the correct syntax highlighting for .php3 files ).

                          I modified the PATHEXT environment variable in Windows XP, from the " 'system' control panel applet->'Advanced' tab->'Environment Variables' button-> 'System variables' text area".

                          Then from control panel "Folder Options" applet-> 'File Types' tab, I added a new file extention (php3), using the button 'New'  and typing php3 in the window that pops up.

                          Then in the 'Details for php3 extention' area I used the 'Change' button to look for the Php.exe executable so that the php3 file extentions are associated with the php executable.

                          You have to modify also the 'PATH' environment variable, pointing to the folder where the php executable is installed

                          Hope this is useful to somebody
                          up
                          0
                          Popeye at P-t-B dot com
                          16 years ago
                          In *nix systems, use the WHICH command to show the location of the php binary executable. This is the path to use as the first line in your php shell script file. (#!/path/to/php -q) And execute php from the command line with the -v switch to see what version you are running.

                          example:

                          # which php
                          /usr/local/bin/php
                          # php -v
                          PHP 4.3.1 (cli) (built: Mar 27 2003 14:41:51)
                          Copyright (c) 1997-2002 The PHP Group
                          Zend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologies

                          In the above example, you would use: #!/usr/local/bin/php

                          Also note that, if you do not have the current/default directory in your PATH (.), you will have to use ./scriptfilename to execute your script file from the command line (or you will receive a "command not found" error). Use the ENV command to show your PATH environment variable value.
                          up
                          0
                          wanna at stay dot anonynous dot com
                          16 years ago
                          TIP: If you want different versions of the configuration file  depending on what SAPI is used,just name them php.ini (apache module), php-cli.ini (CLI) and php-cgi.ini (CGI) and dump them all in the regular configuration directory. I.e no need to compile several versions of php anymore!
                          up
                          -1
                          ross at golder dot org
                          9 years ago
                          Note that parsing of the shebang line may not always work as expected...

                          #!/usr/bin/php -dmemory_limit=512M -dsafe_mode=Off
                          <?php

                          print "memory_limit=".ini_get("memory_limit")."\n";
                          print
                          "safe_mode=".ini_get("safe_mode")."\n";

                          ?>

                          gives...

                          $ ./test.php
                          PHP:  Invalid configuration directive
                          memory_limit=512M -dsafe_mode
                          safe_mode=
                          up
                          -1
                          Anonymous
                          11 years ago
                          I find regex and manually breaking up the arguments instead of havingon $_SERVER['argv'] to do it more flexiable this way.

                          cli_test.php asdf asdf --help --dest=/var/ -asd -h --option mew arf moo -z

                              Array
                              (
                                  [input] => Array
                                      (
                                          [0] => asdf
                                          [1] => asdf
                                      )

                                  [commands] => Array
                                      (
                                          [help] => 1
                                          [dest] => /var/
                                          [option] => mew arf moo
                                      )

                                  [flags] => Array
                                      (
                                          [0] => asd
                                          [1] => h
                                          [2] => z
                                      )

                              )

                          <?php

                          function arguments ( $args )
                          {
                             
                          array_shift( $args );
                             
                          $args = join( $args, ' ' );

                             
                          preg_match_all('/ (--\w+ (?:[= ] [^-]+ [^\s-] )? ) | (-\w+) | (\w+) /x', $args, $match );
                             
                          $args = array_shift( $match );

                             
                          /*
                                  Array
                                  (
                                      [0] => asdf
                                      [1] => asdf
                                      [2] => --help
                                      [3] => --dest=/var/
                                      [4] => -asd
                                      [5] => -h
                                      [6] => --option mew arf moo
                                      [7] => -z
                                  )
                              */

                             
                          $ret = array(
                                 
                          'input'    => array(),
                                 
                          'commands' => array(),
                                 
                          'flags'    => array()
                              );

                              foreach (
                          $args as $arg ) {

                                 
                          // Is it a command? (prefixed with --)
                                 
                          if ( substr( $arg, 0, 2 ) === '--' ) {

                                     
                          $value = preg_split( '/[= ]/', $arg, 2 );
                                     
                          $com   = substr( array_shift($value), 2 );
                                     
                          $value = join($value);

                                     
                          $ret['commands'][$com] = !empty($value) ? $value : true;
                                      continue;

                                  }

                                 
                          // Is it a flag? (prefixed with -)
                                 
                          if ( substr( $arg, 0, 1 ) === '-' ) {
                                     
                          $ret['flags'][] = substr( $arg, 1 );
                                      continue;
                                  }

                                 
                          $ret['input'][] = $arg;
                                  continue;

                              }

                              return
                          $ret;
                          }

                          print_r( arguments( $argv ) );

                          ?>
                          up
                          -1
                          Wade
                          9 years ago
                          I've just found that the fact that the CLI does *not* change the current directory will make include() and require() calls with relative paths fail. This is because they are relative to the current directory, not to the current executing file, the documentation notwithstanding. In CGI mode, this is the same because it changes the current directory.

                          One solution is to call the CGI binary rather than the CLI one. A better solutions is to use dirname(__FILE__) in your path names.
                          up
                          -1
                          punk at studionew dot com
                          15 years ago
                          You can use this function to ask user to enter something.

                          <?php
                          function read ($length='255')
                          {
                             if (!isset (
                          $GLOBALS['StdinPointer']))
                             {
                               
                          $GLOBALS['StdinPointer'] = fopen ("php://stdin","r");
                             }
                            
                          $line = fgets ($GLOBALS['StdinPointer'],$length);
                             return
                          trim ($line);
                          }

                          // then

                          echo "Enter your name: ";
                          $name = read ();
                          echo
                          "\nHello $name! Where you came from? ";
                          $where = read ();
                          echo
                          "\nI see. $where is very good place.";
                          ?>
                          up
                          -2
                          coffear at gmail dot com
                          9 years ago
                          In the notes it there is an example of running 1 line of PHP using:

                          php -r 'print_r(get_defined_constants());'

                          This might work on a UNIX machine but unfortunately on windows it produces the following error message:

                          Parse error: parse error in Command line code on line 1

                          Instead of using ' (single quotes) to encompass the PHP code use " (double quotes) instead. You can safely use ' within the code itself however such as:

                          php -r "echo 'hello';"
                          up
                          -3
                          me at unreal4u dot com
                          7 years ago
                          You could use the Linux way of knowing that everything went ok by dying with a numeric code: 0 if everything went ok and practically anything else if something goes terribly wrong. That way;

                          <?php // hello.php
                          echo 'hello';
                          exit(
                          0);
                          ?>
                          <?php
                          // bye.php
                          echo 'bye';
                          exit(
                          1);
                          ?>
                          <?php
                          // hello-again.php
                          echo 'hi world!';
                          exit(
                          0);
                          ?>

                          calling:
                          php hello.php && php bye.php && php hello-again.php

                          would only execute the first two scripts, the last one doesn't get executed because an error ocurred in that script.

                          Greetings.
                          up
                          -3
                          php at schabdach dot de
                          13 years ago
                          To pass more than 9 arguments to your php-script on Windows, you can use the 'shift'-command in a batch file. After using 'shift', %1 becomes %0, %2 becomes %1 and so on - so you can fetch argument 10 etc.

                          Here's an example - hopefully ready-to-use - batch file:

                          foo.bat:
                          ---------
                          @echo off

                          :init_arg
                          set args=

                          :get_arg
                          shift
                          if "%0"=="" goto :finish_arg
                          set args=%args% %0
                          goto :get_arg
                          :finish_arg

                          set php=C:\path\to\php.exe
                          set ini=C:\path\to\php.ini
                          %php% -c %ini% foo.php %args%
                          ---------

                          Usage on commandline:
                          foo -1 -2 -3 -4 -5 -6 -7 -8 -9 -foo -bar

                          A print_r($argv) will give you all of the passed arguments.
                          up
                          -2
                          merrittd at dhcmc dot com
                          14 years ago
                          Example 43-2 shows how to create a DOS batch file to run a PHP script form the command line using:

                          @c:\php\cli\php.exe script.php %1 %2 %3 %4

                          Here is an updated version of the DOS batch file:

                          @c:\php\cli\php.exe %~n0.php %*

                          This will run a PHP file (i.e. script.php) with the same base file name (i.e. script) as the DOS batch file (i.e. script.bat) and pass all parameters (not just the first four as in example 43-2) from the DOS batch file to the PHP file. 

                          This way all you have to do is copy/rename the DOS batch file to match the name of your PHP script file without ever having to actually modify the contents of the DOS batch file to match the file name of the PHP script.
                          up
                          -2
                          Ben Jenkins
                          14 years ago
                          This took me all day to figure out, so I hope posting it here saves someone some time:
                          Your PHP-CLI may have a different php.ini than your apache-php.  For example: On my Debian-based system, I discovered I have /etc/php4/apache/php.ini and /etc/php4/cli/php.ini
                          If you want MySQL support in the CLI, make sure the line
                          extension=mysql.so
                          is not commented out.
                          The differences in php.ini files may also be why some scripts will work when called through a web browser, but will not work when called via the command line.
                          up
                          -2
                          jgraef at users dot sf dot net
                          12 years ago
                          Hi,
                          This function clears the screen, like "clear screen"

                          <?php
                           
                          function clearscreen($out = TRUE) {
                             
                          $clearscreen = chr(27)."[H".chr(27)."[2J";
                              if (
                          $out) print $clearscreen;
                              else return
                          $clearscreen;
                            }
                          ?>
                          up
                          -2
                          patrick smith
                          10 years ago
                          For command-line option definition and parsing, don't forget about the beauty of getopt().

                          There's a php-native version (http://php.net/getopt) and a PEAR package -- Console_GetOpt (http://pear.php.net/package/Console_Getopt).
                          up
                          -3
                          Willy T. Koch
                          10 years ago
                          I'm figuring out how to pipe an email to a php script with postfix. For the email [email protected]:

                          I created the following line in /etc/aliases:
                          user:        "|/www/file.php"

                          file.php is chmod 755

                          This works fine. But I wanted to test this without having to send an email every time. And this took some searching to figure out, yet it's oh-so simple:

                          To pipe the file email.txt to the script, write the following in the terminal window:

                          [email protected]: php file.php < testepost.txt

                          I was confused by the | in the aliases file, and didn't get what came after what, etc etc.

                          Regards,

                          Willy T. Koch
                          Norway
                          up
                          -3
                          mortals at seznam dot cz
                          11 years ago
                          If a module SAPI is chosen during configure, such as apxs, or the --disable-cgi option is used, the CLI is copied to {PREFIX}/bin/php during make install  otherwise the CGI is placed there.

                          versus

                          Changed CGI install target to php-cgi and 'make install' to install CLI when CGI is selected. (changelog for 5.2.3)
                          http://www.kusq.icu/ChangeLog-5.php#5.2.3
                          up
                          -2
                          jonNO at SPAMjellybob dot co dot uk
                          16 years ago
                          If you want to get the output of a command use the function shell_exec($command) - it returns a string with the output of the command.
                          up
                          -3
                          linus at flowingcreativity dot net
                          13 years ago
                          If you are using Windows XP (I think this works on 2000, too) and you want to be able to right-click a .php file and run it from the command line, follow these steps:

                          1. Run regedit.exe and *back up the registry.*
                          2. Open HKEY_CLASSES_ROOT and find the ".php" key.

                          IF IT EXISTS:
                          ------------------
                          3. Look at the "(Default)" value inside it and find the key in HKEY_CLASSES_ROOT with that name.
                          4. Open the "shell" key inside that key. Skip to 8.

                          IF IT DOESN'T:
                          ------------------
                          5. Add a ".php" key and set the "(Default)" value inside it to something like "phpscriptfile".
                          6. Create another key in HKEY_CLASSES_ROOT called "phpscriptfile" or whatever you chose.
                          7. Create a key inside that one called "shell".

                          8. Create a key inside that one called "run".
                          9. Set the "(Default)" value inside "run" to whatever you want the menu option to be (e.g. "Run").
                          10. Create a key inside "run" called "command".
                          11. Set the "(Default)" value inside "command" to:

                          cmd.exe /k C:\php\php.exe "%1"

                          Make sure the path to PHP is appropriate for your installation. Why not just run it with php.exe directly? Because you (presumably) want the console window to remain open after the script ends.

                          You don't need to set up a webserver for this to work. I downloaded PHP just so I could run scripts on my computer. Hope this is useful!
                          up
                          -5
                          kazink at gmail dot com
                          9 years ago
                          I had problems running php as CGI in thttpd. I have followed instructions posted by db at digitalmediacreation dot ch, but I was still getting "500 Internal Error" answer from the server. However, I had no problems running php as CLI using a simple wrapper file named index.cgi:

                          #!/usr/bin/php
                          <?php
                           
                          require_once 'index.php';
                          ?>

                          but i needed to pass user data through GET and POST, and this method couldn't handle it. I have spent 2 hours figuring out how to run the CGI mode properly, until I finally gave up, and done it in "manual" way. I have just added some code to the wrapper that reads GET and POST data into the proper variables:

                          #!/usr/bin/php
                          <?php

                           
                          //parse the command line into the $_GET variable
                           
                          parse_str($_SERVER['QUERY_STRING'], $_GET);
                           
                           
                          //parse the standard input into the $_POST variable
                           
                          if (($_SERVER['REQUEST_METHOD'] === 'POST')
                             && (
                          $_SERVER['CONTENT_LENGTH'] > 0))
                            {
                             
                          parse_str(fread(STDIN, $_SERVER['CONTENT_LENGTH']), $_POST);
                            }

                            require_once
                          'index.php';
                          ?>

                          It works well for me. It may be useful if someone else have similar problem.
                          up
                          -3
                          dj dot rokx at gmail dot com
                          9 years ago
                          Use PHP as Scripting Language in Windows Vista and 7:

                          ASSOC .phs=PHPScript
                          FTPYE PHPScript=[path to]\php.exe -f "%1" -- %*

                          optional set PATHEXT=.phs;%PATHEXT%

                          now you can execute any php-script (ext: .phs) from the shell like a .vbs or .cmd.

                          "c:\testscript.phs arg1 arg2" or with the optional step "c:\testscript arg1 arg2"

                          i hope this helps somebody.
                          up
                          -3
                          earomero _{at}_ gmail.com
                          11 years ago
                          Here's <losbrutos at free dot fr> function modified to support unix like param syntax like <B Crawford> mentions:

                          <?php
                          function arguments($argv) {
                             
                          $_ARG = array();
                              foreach (
                          $argv as $arg) {
                                  if (
                          preg_match('#^-{1,2}([a-zA-Z0-9]*)=?(.*)$#', $arg, $matches)) {
                                     
                          $key = $matches[1];
                                      switch (
                          $matches[2]) {
                                          case
                          '':
                                          case
                          'true':
                                         
                          $arg = true;
                                          break;
                                          case
                          'false':
                                         
                          $arg = false;
                                          break;
                                          default:
                                         
                          $arg = $matches[2];
                                      }
                                     
                                     
                          /* make unix like -afd == -a -f -d */           
                                     
                          if(preg_match("/^-([a-zA-Z0-9]+)/", $matches[0], $match)) {
                                         
                          $string = $match[1];
                                          for(
                          $i=0; strlen($string) > $i; $i++) {
                                             
                          $_ARG[$string[$i]] = true;
                                          }
                                      } else {
                                         
                          $_ARG[$key] = $arg;   
                                      }           
                                  } else {
                                     
                          $_ARG['input'][] = $arg;
                                  }       
                              }
                              return
                          $_ARG;   
                          }
                          ?>

                          Sample:

                          [email protected] ~/workspace/snipplets $ foxogg2mp3.php asdf asdf --help --dest=/var/ -asd -h
                          Array
                          (
                              [input] => Array
                                  (
                                      [0] => /usr/local/bin/foxogg2mp3.php
                                      [1] => asdf
                                      [2] => asdf
                                  )

                              [help] => 1
                              [dest] => /var/
                              [a] => 1
                              [s] => 1
                              [d] => 1
                              [h] => 1
                          )
                          up
                          -3
                          justin at visunet dot ie
                          16 years ago
                          If you are trying to set up an interactive command line script and you want to get started straight away (works on 4+ I hope). Here is some code to start you off:

                          <?php

                             
                          // Stop the script giving time out errors..
                             
                          set_time_limit(0);

                             
                          // This opens standard in ready for interactive input..
                             
                          define('STDIN',fopen("php://stdin","r"));

                             
                          // Main event loop to capture top level command..
                             
                          while(!0)
                              {
                                 
                                 
                          // Print out main menu..
                                 
                          echo "Select an option..\n\n";
                                  echo
                          "    1) Do this\n";
                                  echo
                          "    2) Do this\n";
                                  echo
                          "    3) Do this\n";
                                  echo
                          "    x) Exit\n";

                                 
                          // Decide what menu option to select based on input..
                                 
                          switch(trim(fgets(STDIN,256)))
                                  {
                                      case
                          1:
                                          break;
                                         
                                      case
                          2:
                                          break;

                                      case
                          3:
                                          break;

                                      case
                          "x":
                                          exit();
                                         
                                      default:
                                          break;
                                  }

                              }

                             
                          // Close standard in..
                             
                          fclose(STDIN);

                          ?>
                          To Top 宁夏11选5开奖直播

                                <em id="gxj5d"></em>
                                  <delect id="gxj5d"><ins id="gxj5d"><form id="gxj5d"></form></ins></delect>
                                  <dl id="gxj5d"></dl><em id="gxj5d"></em>
                                  <div id="gxj5d"><tr id="gxj5d"></tr></div>

                                  <em id="gxj5d"><ol id="gxj5d"><mark id="gxj5d"></mark></ol></em>

                                        <dl id="gxj5d"><ol id="gxj5d"></ol></dl><em id="gxj5d"></em>
                                        <em id="gxj5d"><ol id="gxj5d"></ol></em>
                                        <sup id="gxj5d"><menu id="gxj5d"></menu></sup>
                                            <span id="gxj5d"><form id="gxj5d"><wbr id="gxj5d"></wbr></form></span><dl id="gxj5d"><ins id="gxj5d"></ins></dl>
                                              <div id="gxj5d"><tr id="gxj5d"></tr></div>
                                              <em id="gxj5d"></em>

                                              <em id="gxj5d"><ol id="gxj5d"><thead id="gxj5d"></thead></ol></em>

                                                        <em id="gxj5d"></em>
                                                          <delect id="gxj5d"><ins id="gxj5d"><form id="gxj5d"></form></ins></delect>
                                                          <dl id="gxj5d"></dl><em id="gxj5d"></em>
                                                          <div id="gxj5d"><tr id="gxj5d"></tr></div>

                                                          <em id="gxj5d"><ol id="gxj5d"><mark id="gxj5d"></mark></ol></em>

                                                                <dl id="gxj5d"><ol id="gxj5d"></ol></dl><em id="gxj5d"></em>
                                                                <em id="gxj5d"><ol id="gxj5d"></ol></em>
                                                                <sup id="gxj5d"><menu id="gxj5d"></menu></sup>
                                                                    <span id="gxj5d"><form id="gxj5d"><wbr id="gxj5d"></wbr></form></span><dl id="gxj5d"><ins id="gxj5d"></ins></dl>
                                                                      <div id="gxj5d"><tr id="gxj5d"></tr></div>
                                                                      <em id="gxj5d"></em>

                                                                      <em id="gxj5d"><ol id="gxj5d"><thead id="gxj5d"></thead></ol></em>