PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Παραπομπή Συναρτήσεων> <Χαρακτηριστικά
Last updated: Sun, 25 Nov 2007

view this page in

Χρησιμοποιώντας την PHP από την γραμμή εντολών

Από την έκδοση 4.3.0, η PHP υποστηρίζει ένα νέο τύπο SAPI (Server Application Programming Interface) με όνομα CLI το οποίο σημαίνει Command Line Interface. Όπως υποδηλώνει το όνομα, το επίκεντρο αυτού του τύπου SAPI είναι η ανάπτυξη εφαρμογών για το shell (ή επίσης για desktop) με την PHP. Υπάρχουν αρκετές διαφορές μεταξύ του CLI SAPI και άλλων SAPI τα οποία εξηγούνται σε αυτό το κεφάλαιο. Αξίζει να σημειωθεί πως το CLI και το CGI είναι διαφορετικά SAPI αν και μοιράζονται πολλές ίδιες συμπεριφορές.

Το CLI SAPI έχει κυκλοφορήσει για πρώτο φορά με την PHP 4.2.0, αλλά ήταν ακόμη πειραματικό και έπρεπε να ενεργοποιηθεί ρητά με το --enable-cli όταν έτρεχε το ./configure. Από την PHP 4.3.0 το CLI SAPI δεν είναι πλέον πειραματικό και η επιλογή --enable-cli είναι προεπιλεγμένα ενεργοποιημένη. Μπορείτε να χρησιμοποιήσετε το --disable-cli για να την απενεργοποιήσετε.

Από την PHP 4.3.0, το όνομα, τοποθεσία και η ύπαρξη των CLI/CGI binaries θα διαφέρει ανάλογα με τον τρόπο που εγκαταστάθηκε η PHP στο σύστημα σας. Ως προεπιλογή, όταν εκτελείται το make, τόσο το CGI όσο και το CLI γίνονται build και τοποθετούνται ως sapi/cgi/php και sapi/cli/php αντίστοιχα, στον κατάλογο του source της php. Θα προσέξετε πως και τα δύο έχουν όνομα php. Αυτό που συμβαίνει κατά τη διάρκεια του make install εξαρτάται από τη γραμμή του configure σας. Αν ένα module SAPI επιλεγεί στο configure, όπως το apxs, ή η επιλογή --disable-cgi χρησιμοποιηθεί, το CLI αντιγράφεται στο {PREFIX}/bin/php στη διάρκεια του make install αλλιώς το CGI τοποθετείται εκεί. Έτσι, για παράδειγμα, αν το --with--apxs βρίσκεται στην configure γραμμή σας, το CLI αντιγράφεται στο {PREFIX}/bin/php κατά τη διάρκεια του make install. Αν θέλετε να παρακάμψετε την εγκατάσταση του CGI binary, χρησιμοποιήστε το make install-cli μετά το make install. Εναλλακτικά μπορείτε να ορίσετε το --disable-cgi στην configure γραμμή σας.

Note: Επειδή τόσο το --enable-cli όσο και το --enable-cgi είναι ενεργοποιημένα by default (ως προεπιλογή), απλά έχοντας το --enable-cli στην configure γραμμή σας δεν σημαίνει απαραίτητα πως το CLI θα αντιγραφεί ως {PREFIX}/bin/php κατά το make install.

Τα windows πακέτα μεταξύ της PHP 4.2.0 και της PHP 4.2.3 έδιναν το CLI σαν php-cli.exe, έχοντας το στον ίδιο κατάλογο με το CGI php.exe. Από την PHP 4.3.0 το windows πακέτο δίνει το CLI σαν php.exe σε ένα ξεχωριστό κατάλογο με όνομα cli, έτσι cli/php.exe.

Note: Τι SAPI έχω; Από ένα shell, η εντολή php -v θα σας πει αν η php είναι CGI ή CLI. Δείτε επίσης τη συνάρτηση php_sapi_name() και τη σταθερά PHP_SAPI.

Note: Μια manual σελίδα του unix έχει προστεθεί στην PHP 4.3.2. Μπορείτε να την δείτε γράφοντας man php στο shell περιβάλλον σας.

Οι κύριες διαφορές του CLI SAPI συγκριτικά με το SAPI είναι:

  • Αντίθετα με το CGI SAPI, δεν εκτυπώνονται headers στην έξοδο.

    Αν και το CGI SAPI προσφέρει ένα τρόπο για να μην φανούν HTTP headers, δεν υπάρχει παρόμοιος διακόπτης για να τους ενεργοποιήσει κανείς στο CLI SAPI.

    Το CLI ξεκινά σε quiet mode ως προεπιλογή, αν και ο -q διακόπτης κρατιέται για συμβατότητα για να μπορείτε να το χρησιμοποιείτε σε παλαιότερα CGI scripts.

    Δεν αλλάζει τον working κατάλογο σε αυτόν του script. (Ο διακόπτης -C υπάρχει για συμβατότητα)

    Απλά μηνύματα λάθους σε μορφή κειμένου (δεν υπάρχει HTML μορφοποίηση).

  • Υπάρχουν συγκεκριμένα php.ini directives τα οποία γίνονται override από το CLI SAPI επειδή δεν έχουν νόημα σε shell περιβάλλοντα:

    php.ini directives που γίνονται οverride
    Directive Προεπιλεγμένη τιμή του CLI SAPI Σχόλια
    html_errors FALSE Μπορεί να είναι αρκετά δύσκολο να διαβαστούν τα μηνύματα σφαλμάτων στο shell όταν είναι γεμάτα με όλα εκείνα τα άσκοπα HTML tags, έτσι αυτό το έχει ως προεπιλογή το FALSE.
    implicit_flush TRUE Είναι θεμιτό οποιαδήποτε έξοδος προερχόμενη από τις print(), echo() και τους φίλους τους να γράφεται αμέσως στο output και να μην γίνονται cache σε κάποιο buffer. Μπορείτε ακόμη να χρησιμοποιήσετεoutput buffering αν θέλετε να αναβάλλετε ή να χειριστείτε το standard output.
    max_execution_time 0 (unlimited) Λόγω των άπειρων δυνατοτήτων στη χρήση της PHP σε περιβάλλοντα shell, ο μέγιστος χρόνος εκτέλεσης έχει οριστεί να είναι απεριόριστος. Εκεί που οι εφαρμογές γραμμένες για το web συχνά εκτελούνται πολύ γρήγορα, οι shell εφαρμογές τείνουν να έχουν πολύ μεγαλύτερο χρόνο εκτέλεσης.
    register_argc_argv TRUE

    Επειδή αυτή η ρύθμιση είναι TRUE πάντα θα έχετε πρόσβαση στο argc (ο αριθμός των arguments που περνιούνται στην εφαρμογή) και το argv (array των ίδιων των argument) στο CLI SAPI.

    Από την PHP 4.3.0, οι PHP μεταβλητές $argc και $argv καταχωρούνται και τιμολογούνται με τις ανάλογες τιμές όταν χρησιμοποιείται το CLI SAPI. Πριν από αυτή την έκδοση, η δημιουργία αυτών των μεταβλητών συμπεριφερόταν όπως γίνεται στις CGI και MODULE εκδόσεις που απαιτούν το PHP directive register_globals να είναι ενεργοποιημένο. Ανεξάρτητα της έκδοσης ή της register_globals ρύθμισης, μπορείτε πάντα να πάτε μέσω του $_SERVER ή του $HTTP_SERVER_VARS. Για παράδειγμα: $_SERVER['argv']

    Note: Αυτά τα directives δεν μπορούν να αρχικοποιηθούν με κάποια άλλη τιμή από το αρχείο ρυθμίσεων php.ini ή ένα προσωπικό (αν οριστεί). Αυτός είναι ένας περιορισμός επειδή αυτές οι τιμές εφαρμόζονται μετά που αναλύονται όλα τα αρχεία ρυθμίσεων. Ωστόσο, οι τιμές τους μπορούν να αλλαχτούν κατά το runtime (κάτι το οποίο δεν έχει νόημα για όλα εκείνα τα directives, π.χ. register_argc_argv).

  • Για να γίνει πιο εύκολη η εργασία στο περιβάλλον του shell, οι παρακάτω σταθερές ορίζονται:

    Σταθερές ειδικές για το CLI
    Σταθερά Περιγραφή
    STDIN Ένα ήδη ανοιχτό stream στο stdin. Αυτό αποθηκεύεται ανοίγοντας το με την
    $stdin = fopen('php://stdin', 'r');
    STDOUT Ένα ήδη ανοιχτό stream στο stdout. Αυτό αποθηκεύεται ανοίγοντας το με την
    $stdout = fopen('php://stdout', 'w');
    STDERR Ένα ήδη ανοιχτό stream στο stderr. Αυτό αποθηκεύεται ανοίγοντας το με την
    $stderr = fopen('php://stderr', 'w');

    Δεδομένων των παραπάνω, αδεν χρειάζεστε να ανοίξετε π.χ. ένα stream για το stderr οι ίδιοι, απλά χρησιμοποιήστε τη σταθερά αντί του ίδιου του stream resource:

    php -r 'fwrite(STDERR, "stderr\n");'
    Δεν χρειάζεται να κλείσετε ρητά αυτά τα stream, μια και κλείνονται αυτόματα από την PHP όταν το script τερματίζει.

  • Το CLI SAPI δεν αλλάζει τον τρέχων κατάλογο στον κατάλογο του script που εκτελείται!

    Παράδειγμα που δείχνει τις διαφορές στο CGI SAPI:

    <?php
        
    /* Our simple test application named test.php*/
        
    echo getcwd(), "\n";
    ?>

    Όταν χρησιμοποιείτε την CGI έκδοση, η έξοδος είναι:

    $ pwd
    /tmp
    
    $ php -q another_directory/test.php
    /tmp/another_directory
    
    Αυτό δείχνει καθαρά ότι η PHP αλλάζει τον τρέχων κατάλογο σε αυτό του script που εκτελείται.

    Χρησιμοποιώντας το CLI SAPI γίνεται:

    $ pwd
    /tmp
    
    $ php -f another_directory/test.php
    /tmp
    
    Αυτό επιτρέπει μεγαλύτερη ευελιξία όταν γράφετε shell εργαλεία με την PHP.

    Note: Το CGI SAPI υποστηρίζει την CLI SAPI συμπεριφορά μέσω του -C switch όταν εκτελείται από την γραμμή εντολών.

Η λίστα των επιλογών του command line options που δίνεται με το PHP binary μπορούν να ερωτηθούν ανά πάσα στιγμή τρέχοντας την PHP με το -h switch:

Usage: php [options] [-f] <file> [args...]
       php [options] -r <code> [args...]
       php [options] [-- args...]
  -s               Display colour syntax highlighted source.
  -w               Display source with stripped comments and whitespace.
  -f <file>        Parse <file>.
  -v               Version number
  -c <path>|<file> Look for php.ini file in this directory
  -a               Run interactively
  -d foo[=bar]     Define INI entry foo with value 'bar'
  -e               Generate extended information for debugger/profiler
  -z <file>        Load Zend extension <file>.
  -l               Syntax check only (lint)
  -m               Show compiled in modules
  -i               PHP information
  -r <code>        Run PHP <code> without using script tags <?..?>
  -h               This help

  args...          Arguments passed to script. Use -- args when first argument 
                   starts with - or script is read from stdin

Το CLI SAPI έχει τρεις διαφορετικούς τρόπους για να πάρει τον PHP κώδικα που θέλετε να εκτελέσετε:

  1. Λέγοντας της PHP να εκτελέσει ένα συγκεκριμένο αρχείο.

    php my_script.php
    
    php -f my_script.php
    
    Και οι δύο τρόποι (χρησιμοποιώντας το -f switch ή όχι) εκτελούν το αρχείο my_script.php. Μπορείτε να διαλέξετε οποιοδήποτε αρχείο για να εκτελεστεί - τα PHP script σας δεν χρειάζεται να τελειώνουν με την .php επέκταση αλλά μπορείτε να έχετε οποιοδήποτε όνομα ή επέκταση θέλετε.

  2. Δίνοντας τον PHP κώδικα προς εκτέλεση κατ' ευθείαν στην γραμμή εντολών.

    php -r 'print_r(get_defined_constants());'
    
    Προσοχή πρέπει να δίνεται σχετικά με την αντικατάσταση των μεταβλητών του shell και τη χρήση εισαγωγικών (quoting).

    Note: Διαβάστε το παράδειγμα προσεκτικά, δεν υπάρχουν tags αρχής ή τέλους! Το -r switch απλά δεν τις χρειάζεται. Χρησιμοποιώντας τις θα οδηγήσει σε ένα σφάλμα του μεταφραστή.

  3. Δίνοντας τον PHP κώδικα προς εκτέλεση μέσω του standard input (stdin).

    Αυτό δίνει την ισχυρή δυνατότητα δυναμικής δημιουργίας PHP κώδικα και τροφοδοσίας του στο binary, όπως φαίνεται σε αυτό το (φανταστικό) παράδειγμα:

    $ some_application | some_filter | php | sort -u >final_output.txt
    

Δεν μπορείτε να συνδιάσετε οποιουσδήποτε από τους τρεις κώδικες για να εκτελέσετε κώδικα.

Όπως οποιαδήποτε shell εφαρμογή, το PHP binary δέχεται ένα αριθμό από ορίσματα (arguments) αλλά το PHP script μπορεί επίσης να δεχτεί ορίσματα. Ο αριθμός των ορισμάτων που μπορούν να περαστούν στο script σας δεν περιορίζεται από την PHP (το shell έχει ένα ορισμένο όριο μεγέθους του αριθμού των χαρακτήρων που μπορούν να περαστούν, συνήθως δεν θα φτάσετε αυτό το όριο). Τα arguments που περνιούνται στο script σας είναι διαθέσιμα μέσω του global array $argv. Ο μηδενικός δείκτης (index) πάντα περιέχει το όνομα του script (το οποίο είναι - σε περίπτωση που ο PHP κώδικας έρχεται από είτε το standard input ή από το switch της γραμμής εντολών -r). Η δεύτερη registered global μεταβλητή είναι η $argc η οποία περιέχει τον αριθμό των στοιχείων στο $argv array (όχι τον αριθμό των arguments που δίνονται στο script).

Όσο τα arguments που θέλετε να περάσετε στο script σας δεν αρχίζουν με τον χαρακτήρα -, δεν υπάρχει τίποτα ιδιαίτερο που πρέπει να προσέξετε. Περνώντας ένα argument στο script σας το οποίο αρχίζει με - θα δημιουργήσει προβλήματα επειδή η ίδια η PHP νομίζει πως πρέπει να το χειριστεί. Για να το αποφύγετε αυτό, χρησιμοποιήστε το argument list separator (διαχωριστής) --. Μετά που αναλύεται αυτός ο διαχωριστής στην PHP, κάθε argument που ακολουθεί περνιέται ανέπαφος στο script σας.

# This will not execute the given code but will show the PHP usage
$ php -r 'var_dump($argv);' -h
Usage: php [options] [-f] <file> [args...]
[...]

# This will pass the '-h' argument to your script and prevent PHP from showing it's usage
$ php -r 'var_dump($argv);' -- -h
array(2) {
  [0]=>
  string(1) "-"
  [1]=>
  string(2) "-h"
}

Ωστόσο, υπάρχει ακόμη ένας τρόπος χρήσης της PHP για shell scripting. Μπορείτε να γράψετε ένα script όπου η πρώτη γραμμή αρχίζει με #!/usr/bin/php. Ακολουθώντας αυτό μπορείτε να τοποθετήσετε κανονικό PHP κώδικα μεταξύ των PHP tags αρχής και τέλους. Από τη στιγμή που έχετε ορίσει τα attribute εκτέλεσης του αρχείου κατάλληλα (π.χ. chmod +x test) το script σας μπορεί να εκτελεστεί όπως ένα κανονικό shell ή perl script:

#!/usr/bin/php
<?php
    var_dump
($argv);
?>
Υποθέτοντας ότι αυτό το αρχείο έχει όνομα test στον παρών κατάλογο, μπορείτε τώρα να κάνετε το ακόλουθο:
$ chmod 755 test
$ ./test -h -- foo
array(4) {
  [0]=>
  string(6) "./test"
  [1]=>
  string(2) "-h"
  [2]=>
  string(2) "--"
  [3]=>
  string(3) "foo"
}
Όπως βλέπετε, σε αυτή την περίπτωση δεν χρειάζεται να δοθεί σημασία όταν περνιούνται παράμετροι που αρχίζουν με το - στο script σας.

Επιλογές γραμμής εντολών
Επιλογή Περιγραφή
-s

Εμφανίζει κώδικα με χρηματικό syntax highlighting.

Αυτή η επιλογή χρησιμοποιεί τον εσωτερικό μηχανισμό ανάλυσης του αρχείου και παράγει μια HTML highlighted έκδοση του και το γράφει στοο standard output. Σημειώστε πως το μόνο που κάνει είναι να παράγει ένα μπλοκ από <code> [...] </code> HTML tags, όχι HTML headers.

Note: Αυτή η επιλογή δεν λειτουργεί μαζί με το -r option.

-w

Εμφανίζει κώδικα με αφαιρεμένα τα σχόλια και τους κενούς χαρακτήρες.

Note: Αυτή η επιλογή δεν δουλεύει μαζί με την επιλογή-r.

-f

Μεταφράζει και εκτελεί το δοσμένο αρχείο στην -f επιλογή. Αυτό το switch είναι προαιρετικό και μπορεί να παραληφθεί. Απλά παρέχοντας το όνομα του αρχείου προς εκτέλεση είναι αρκετό.

-v

Γράφει τις εκδόσεις των PHP, PHP SAPI, και Zend στο standard output, π.χ.

$ php -v
PHP 4.3.0 (cli), Copyright (c) 1997-2002 The PHP Group
Zend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologies

-c

Με αυτή την επιλογή κάποιος μπορεί είτε να ορίσει ένα κατάλογο όπου θα αναζητηθεί το php.ini είτε να ορίσει ένα προσωπικό αρχείο INI απ' ευθείας (το οποίο δεν χρειάζεται να ονομάζεται php.ini), π.χ.:

$ php -c /custom/directory/ my_script.php

$ php -c /custom/directory/custom-file.ini my_script.php

-a

Τρέχει την PHP interactively.

-d

Αυτή η επιλογή σας επιτρέπει να ορίσετε μια προσωπική τιμή για οποιοδήποτε από τα directive ρυθμίσεων που επιτρέπονται στο php.ini. Η σύνταξη είναι:

-d configuration_directive[=value]

Παραδείγματα:

# Omitting the value part will set the given configuration directive to "1"
$ php -d max_execution_time -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(1) "1"

# Passing an empty value part will set the configuration directive to ""
php -d max_execution_time= -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(0) ""

# The configuration directive will be set to anything passed after the '=' character
$  php -d max_execution_time=20 -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(2) "20"
$  php -d max_execution_time=doesntmakesense -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(15) "doesntmakesense"

-e

Παράγει εκτενείς πληροφορίες για τον debugger/profiler.

-z

Φορτώνει την Zend επέκταση. Αν μόνο ένα όνομα αρχείο δοθεί, η PHP προσπαθεί να φορτώσει την επέκταση από το παρών path βιβλιοθηκών στο σύστημα σας (συνήθως ορίζεται το /etc/ld.so.conf στα Linux συστήματα). Περνώντας ένα όνομα αρχείο με ένα absolute (απόλυτο) path δεν θα χρησιμοποιθεί το path αναζήτησης βιβλιοθηκών του συστήματος. Ένα relative (σχετικό) όνομα αρχείου με κατάλογο θα κάνει την PHP να προσπαθήσει να φορτώσει την επέκταση στον κατάλογο σχετικά (relative) στον τρέχων κατάλογο.

-l

Αυή η επιλογή προσφέρει ένα βολικό τρόπο να γίνεται απλά ένας έλεγχος σύνταξης στον δοσμένο PHP κώδικα. Σε επιτυχία, το κείμενο No syntax errors detected in <filename> γράφεται στο standard output και το shell return code είναι 0. Σε αποτυχία, το κείμενο Errors parsing <filename> επιπρόσθετα στο κείμενο σφαλμάτων του εσωτερικού μεταφραστή γράφεται στο standard output και το shell return code ορίζεται σε 255.

Αυτή η επιλογή δεν θα βρει fatal σφάλματα (όπως undefined συναρτήσεις). Χρησιμοποιήστε το -f αν θέλετε να ελέγξετε και για fatal σφάλματα.

Note: Αυτή η επιλογή δεν δουλεύει μαζί με την -r επιλογή.

-m

Χρησιμοποιώντας αυτή την επιλογή, η PHP εκτυπώνει τα built-in (και φορτωμένα) PHP και Zend modules:

$ php -m
[PHP Modules]
xml
tokenizer
standard
session
posix
pcre
overload
mysql
mbstring
ctype

[Zend Modules]

-i Αυτή η command line επιλογή καλεί την phpinfo(), και εκτυπώνει τα αποτελέσματα. Αν η PHP δεν δουλεύει σωστά, συμβουλεύεστε να χρησιμοποιήσετε το php -i και να δείτε αν οποιαδήποτε μηνήματα σφαλμάτων εκτυπώνονται πριν ή στη θέση των πινάκων πληροφοριών. Προσέξτε πως η έξοδος είναι σε HTML και έτσι αρκετά μεγάλη.
-r

Αυτή η επιλογή επιτρέπει την εκτέλεση της PHP ακριβώς μέσω της γραμμής εντολών. Τα PHP tags αρχής και τέλους (<?php και ?>) δεν χρειάζονται και θα προκαλέσουν ένα σφάλμα μεταφραστή αν υπάρχουν.

Note: Πρέπει να δίνεται προσοχή στη χρήση αυτής της μορφής της PHP ώστε να μην υπάρχει σύγκρουση με την αντικατάσταση μεταβλητών της γραμμής εντολών που γίνεται από το shell.
Παράδειγμα που δείχνει ένα σφάλμα του μεταφραστή (parser error):

$ php -r "$foo = get_defined_constants();"
Command line code(1) : Parse error - parse error, unexpected '='
Το πρόβλημα εδώ είναι ότι το sh/bash εκτελεί αντικατάσταση μεταβλητών ακόμη και όταν χρησιμοποιούνται εισαγωγικά (double quotes) ". Μια και η μεταβλητή $foo είναι απίθανο να έχει οριστεί, δεν αντιστοιχεί σε τίποτα (expands to nothing) το οποίο έχει ως αποτέλεσμα ο κώδικας που δίνεται στην PHP για εκτέλεση να είναι στην πραγματικότητα:
$ php -r " = get_defined_constants();"
Ο σωστός τρόπος θα ήταν να χρησιμοποιηθούν μονά εισαγωγικά (single quotes) '. Οι μεταβλητές σε string που είναι single-quoted δεν αντικαθιστώνται από το sh/bash.
$ php -r '$foo = get_defined_constants(); var_dump($foo);'
array(370) {
  ["E_ERROR"]=>
  int(1)
  ["E_WARNING"]=>
  int(2)
  ["E_PARSE"]=>
  int(4)
  ["E_NOTICE"]=>
  int(8)
  ["E_CORE_ERROR"]=>
  [...]
Αν χρησιμοποιείτε ένα shell διαφορετικό από το sh/bash, μπορεί να βιώσετε και άλλα προβλήματα. Νιώστε ελεύθεροι να ανοίξετε ένα bug report ή να στείλετε ένα mail στο phpdoc@lists.php.net. Υπάρχει περίπτωση κάποιος εύκολα να συναντήσει προβλήματα όταν προσπαθεί να βάλει τις shell μεταβλητές μέσα στον κώδικα ή να χρησιμοποιήσει backslash για escaping. Έχετε προειδοποιηθεί.

Note: Το -r είναι διαθέσιμο στο CLI SAPI και όχι στο CGI SAPI.

-h Με αυτή την επιλογή, μπορείτε να πάρετε πληροφορίες σχετικά με την ακριβή λίστα των επιλογών της γραμμής εντολών και κάποιες περιγραφές της μιας γραμμής για το τι κάνουν.

Το εκτελέσιμο της PHP μπορεί να χρησιμοποιηθεί για να τρέξουν script της PHP απόλυτα ανεξάρητα από τον web server. Αν είστε σε ένα Unix σύστημα, θα πρέπει να προσθέσετε μια ειδική πρώτη γραμμή στο PHP script σας, και να το κάνετε εκτελέσιμο, ώστε το σύστημα να ξέρει, ποιό πρόγραμμα θα πρέπει να τρέξει το script. Σε ένα Windows σύστημα μπορείτε να συσχετίσετε το php.exe με την double click επιλογή των .php αρχείων, ή να κάνετε ένα batch αρχείο να τρέχει το script μέσω της PHP. Η πρώτη γραμμή που προστίθεται στο script για να δουλεύει στο Unix δεν θα βλάψει στα Windows, έτσι μπορείτε να γράψετε cross platform προγράμματα με αυτό τον τρόπο. Ένα απλό παράδειγμα γραφής ενός προγράμματος PHP της γραμμής εντολών μπορεί να βρεθεί παρακάτω.

Example#1 Ένα Script που προορίζεται να τρέξει από την γραμμή εντολών (script.php)

#!/usr/bin/php
<?php

if ($argc != || in_array($argv[1], array('--help''-help''-h''-?'))) {
?>

This is a command line PHP script with one option.

  Usage:
  <?php echo $argv[0]; ?> <option>

  <option> can be some word you would like
  to print out. With the --help, -help, -h,
  or -? options, you can get this help.

<?php
} else {
    echo 
$argv[1];
}
?>

Στο παραπάνω script, χρησιμοποιήσαμε την ειδική πρώτη γραμμή για να δείξουμε πως αυτό το αρχείο θα πρέπει να εκτελεστεί από την PHP. Δουλεύουμε με μια CLI έκδοση εδώ, έτσι δεν θα υπάρχουν εκτυπώσεις από HTTP headers. Υπάρχουν δύο μεταβλητές που μπορείτε να χρησιμοποιήσετε όταν γράφετε εφαρμογές γραμμής εντολών με την PHP: Οι $argc και $argv. Η πρώτη αποτελεί τον αριθμό των argument συν ένα (το όνομα του script που εκτελείται). Η δεύτερη είναι ένα array το οποίο περιέχει τα arguments, αρχίζοντας με το όνομα του script σαν τον αριθμό μηδέν ($argv[0]).

Στο παραπάνω πρόγραμμα ελέγξαμε αν υπάρχουν λιγότερα ή περισσότερα από ένα arguments. Επίσης αν το argument ήταν --help, -help, -h ή -?, εκτυπώσαμε ένα μήνυμα βοήθειας, εκτυπώνοντας το όνομα του script δυναμικά. Αν λαμβάναμε κάποια άλλα argument τα εκτυπώναμε και αυτά.

Αν θέλατε να εκτελέσετε το παραπάνω script στο Unix, χρειάζεται να το κάνετε εκτελέσιμο και απλά να το καλέσετε με το script.php echothis ή script.php -h. Στα Windows, μπορείτε να δημιουργήσετε ένα batch αρχείο για αυτό το σκοπό:

Example#2 Αρχείο Batch για να εκτελεστεί ένα PHP script γραμμής εντολών (script.bat)

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

Υποθέτοντας πως ονομάσατε το παραπάνω πρόγραμμα script.php, και έχετε το CLI php.exe σας στο c:\php\cli\php.exe αυτό το batch αρχείο θα εκτελεστεί για σας με τις επιπλέον επιλογές: script.bat echothis ή script.bat -h.

Δείτε επίσης το documentation (τεκμηρίωση) της Readline επέκτασης για περισσότερες συναρτήσεις που μπορείτε να χρησιμοποιήσετε για να βελτιώσετε τις εφαρμογές γραμμής εντολών σας στην PHP.



add a note add a note User Contributed Notes
Χρησιμοποιώντας την PHP από την γραμμή εντολών
the_bloke AT norway.no
12-May-2008 05:08
An informational post in the hope that others might save some frustration:
(Keywords: mod_rewrite, rewritemap, extension not present )

After upgrading from 5.0.x -> 5.2.5 -> 5.2.6 my rewritemaps in apache (PHP scripts loaded through httpd.conf) became useless.
These use PHPCLI to execute.
I got the error:
Extension 'inputfilenamehere.php' not present.

First I had the --q param, (-q caused errors back in 2005 when the server was set up), removed this, replaced with -q, didn't work.
When editing the bashline options in the file, cli would sporadically give me either:
-bash: ./inputfilenamehere.php: /usr/bin/php^M: bad interpreter: No such file or directory
or an error along the lines of:
Cannot find the input file: *blankspacehere*

After creating a new .php file and typing the bashline manually then copying the text from one of the broken files into the new one, everything worked.

See also these posts for somewhat similar errors:
 goalain eat gmail dont com
21-Aug-2006 09:20
If your php script doesn't run with shebang (#!/usr/bin/php).....
&&
db at digitalmediacreation dot ch
22-Feb-2005 08:49
A very important point missing...
mortals at seznam dot cz
07-May-2008 01:08
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.php.net/ChangeLog-5.php#5.2.3
safak ozpinar
29-Feb-2008 06:32
When you want to get inputs from STDIN, you may use this function if you like using C coding style.

<?php
// up to 8 variables

function scanf($format, &$a0=NULL, &$a1=NULL, &$a2=NULL, &$a3=NULL,
                        &
$a4=NULL, &$a5=NULL, &$a6=NULL, &$a7=NULL)
{
   
$num_args = func_num_args();
    if(
$num_args > 1) {
       
$inputs = fscanf(STDIN, $format);
        for(
$i=0; $i<$num_args-1; $i++) {
           
$arg = 'a'.$i;
            $
$arg = $inputs[$i];
        }
    }
}

scanf("%d", $number);

?>
Anonymous
18-Feb-2008 03:29
another command line tool for php coders, "zD builder"
Anonymous
16-Feb-2008 09:29
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 ) );

?>
technorati at gmail dot com
12-Feb-2008 06:21
Here's an update to the script a couple of people gave below to read arguments from $argv of the form --name=VALUE and -flag. Changes include:

Don't use $_ARG - $_ is generally considered reserved for the engine.
Don't use regex where a string operation will do just as nicely
Don't overwrite --name=VALUE with -flag when 'name' and 'flag' are the same thing
Allow for VALUE that has an equals sign in it

function arguments($argv) {
    $ARG = array();
    foreach ($argv as $arg) {
        if (strpos($arg, '--') === 0) {
            $compspec = explode('=', $arg);
            $key = str_replace('--', '', array_shift($compspec));
            $value = join('=', $compspec);
            $ARG[$key] = $value;
        } elseif (strpos($arg, '-') === 0) {
            $key = str_replace('-', '', $arg);
            if (!isset($ARG[$key])) $ARG[$key] = true;
        }
    }
    return $ARG;
}
earomero _{at}_ gmail.com
28-Oct-2007 04:51
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:

eromero@ditto ~/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
)
james_s2010 at NOSPAM dot hotmail dot com
22-Oct-2007 02:11
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.
B Crawford
21-Oct-2007 07:01
I have not seen in this thread any code snippets that support the full *nix style argument parsing. Consider this:

<?php
print_r
(getArgs($_SERVER['argv']));

function
getArgs($args) {
 
$out = array();
 
$last_arg = null;
    for(
$i = 1, $il = sizeof($args); $i < $il; $i++) {
        if( (bool)
preg_match("/^--(.+)/", $args[$i], $match) ) {
        
$parts = explode("=", $match[1]);
        
$key = preg_replace("/[^a-z0-9]+/", "", $parts[0]);
            if(isset(
$parts[1])) {
            
$out[$key] = $parts[1];   
            }
            else {
            
$out[$key] = true;   
            }
        
$last_arg = $key;
        }
        else if( (bool)
preg_match("/^-([a-zA-Z0-9]+)/", $args[$i], $match) ) {
            for(
$j = 0, $jl = strlen($match[1]); $j < $jl; $j++ ) {
            
$key = $match[1]{$j};
            
$out[$key] = true;
            }
        
$last_arg = $key;
        }
        else if(
$last_arg !== null) {
        
$out[$last_arg] = $args[$i];
        }
    }
 return
$out;
}

/*
php file.php --foo=bar -abc -AB 'hello world' --baz

produces:

Array
(
  [foo] => bar
  [a] => true
  [b] => true
  [c] => true
  [A] => true
  [B] => hello world
  [baz] => true
)

*/
?>
losbrutos at free dot fr
27-Sep-2007 05:54
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
)
dino (at) asttra (dot) com (dot) br
16-Aug-2007 12:24
For those who was unable to clear the windows screen trying to run CLS command:

CLS is not an windows executable file! It is an option from command.com!

So, the rigth command is

   system("command /C cls");
lucas dot vasconcelos at gmail dot com
22-Jul-2007 11:04
Just another variant of previous script that group arguments doesn't starts with '-' or '--'

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;
}

$ 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
)
bluej100@gmail
25-Jun-2007 11:02
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.
eric dot brison at anakeen dot com
04-Jun-2007 05:16
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
)
contact at nlindblad dot org
12-May-2007 02:55
While working with command line scripts it is tedious to handle the arguments in a numerated array.

The following code will:

If the argument is of the form –NAME=VALUE it will be represented in the array as an element with the key NAME and the value VALUE. I the argument is a flag of the form -NAME it will be represented as a boolean with the name NAME with a value of true in the associative array.

<?php

function arguments($argv) {
   
$_ARG = array();
    foreach (
$argv as $arg) {
        if (
ereg('--[a-zA-Z0-9]*=.*',$arg)) {
           
$str = split("=",$arg); $arg = '';
           
$key = ereg_replace("--",'',$str[0]);
            for (
$i = 1; $i < count($str); $i++ ) {
               
$arg .= $str[$i];
            }
                       
$_ARG[$key] = $arg;
        } elseif(
ereg('-[a-zA-Z0-9]',$arg)) {
           
$arg = ereg_replace("-",'',$arg);
           
$_ARG[$arg] = 'true';
        }
   
    }
return
$_ARG;
}

?>

Example:

<?php print_r(arguments($argv)); ?>

# php5 myscript.php --user=nobody --password=secret -p

Array
(
    [user] => nobody
    [password] => secret
    [p] => true
)
Jouni
08-Apr-2007 03:27
I had a problem with PHP 5.2.0 (cli) (winXP) that no output was printed when I tried to run any file. Using the -n switch solved the problem.

Apparently the interpreter can't always find php.ini, even though both exist in the same folder and the PATH variable is set correctly. No error messages were printed either.
rob
23-Mar-2007 12:48
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...
djcassis at gmail
09-Mar-2007 07:14
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
jsa1971 at gmail dot com
05-Mar-2007 08:03
python coders might miss this construct when working in PHP:

if __name__=='__main__':
    # handle direct invocation from command line

it's a great way to embed little bits of test code (or a full-on cli for that matter),
while keeping the source file usable in other contexts.

Far as I can tell, this is the closest approximation available in PHP5:

if ('cli'===php_sapi_name() &&
    __FILE__===realpath(
        getcwd().DIRECTORY_SEPARATOR.$_SERVER['argv'][0]
        )) {
    // handle direct invocation from command line
}
jgraef at users dot sf dot net
26-Nov-2006 08:46
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;
  }
?>
goalain eat gmail dont com
14-Nov-2006 12:57
An addition to my previous post (you can replace it)

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
16-Sep-2006 11:05
It seems like 'max_execution_time' doesn't work on CLI.

<?php
php
-d max_execution_time=20
       
-r '$foo = ini_get("max_execution_time"); var_dump($foo);'
?>
will print string(2) "20", but if you'l run infinity while: while(true) for example, it wouldn't stop after 20 seconds.
Testes on Linux Gentoo, PHP 5.1.6.
hobby6_at_hotmail.com
15-Sep-2006 03:59
On windows, you can simulate a cls by echoing out just \r.  This will keep the cursor on the same line and overwrite what was on the line.

for example:

<?php
   
echo "Starting Iteration" . "\n\r";
    for (
$i=0;$i<10000;$i++) {
        echo
"\r" . $i;
    }
    echo
"Ending Iteration" . "\n\r";
?>
goalain eat gmail dont com
21-Aug-2006 12:20
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 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
stromdotcom at hotmail dot com
21-Feb-2006 10:27
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
drewish at katherinehouse dot com
25-Sep-2005 12:08
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'));"
OverFlow636 at gmail dot com
19-Sep-2005 12:27
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];
    }
}
?>
php at schabdach dot de
16-Sep-2005 09:06
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.
Lasse Johansson
18-Aug-2005 01:53
Hi, parsing the commandline (argv) can be very simple in PHP.
If you use keyword parms like:

script.php parm1=value parm3=value

All you have to do in script.php is:

for ($i=1; $i < $argc; $i++) {parse_str($argv[$i]);}
$startup=compact('parm1', 'parm2', 'parm3');
docey
14-Jul-2005 05:44
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.
wallacebw
24-Jun-2005 08:07
For windows clearing the screen using "system('cls');" does not work (at least for me)...

Although this is not pretty it works... Simply send 24 newlines after the output (for one line of output, 23 for two, etc

Here is a sample function and usage:

    function CLS($lines){  // $lines = number of lines of output to keep
        for($i=24;$i>=$lines;$i--) @$return.="\n";
        return $return;
    }
 
    fwrite(STDOUT,"Still Processing: Total Time ".$i." Minutes so far..." . CLS(1));

Hope This Helps,
Wallacebw
linus at flowingcreativity dot net
30-May-2005 07:32
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!
roberto dot dimas at gmail dot com
26-May-2005 01:52
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
diego dot rodrigues at poli dot usp dot br
02-May-2005 08:29
#!/usr/bin/php -q
<?
/**********************************************
* Simple argv[] parser for CLI scripts
* Diego Mendes Rodrigues - So Paulo - Brazil
* diego.m.rodrigues [at] gmail [dot] com
* May/2005
**********************************************/

class arg_parser {
    var $argc;
    var $argv;
    var $parsed;
    var $force_this;

    function arg_parser($force_this="") {
        global $argc, $argv;
        $this->argc = $argc;
        $this->argv = $argv;
 &