Write about the running php script

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    PHP Installation for Windows Users: Follow the steps to install PHP on the Windows operating system.

    • Step 1: First, we have to download PHP from it’s official website. We have to download the .zip file from the respective section depending upon on our system architecture[x86 or x64].
    • Step 2: Extract the .zip file to your preferred location. It is recommended to choose the Boot Drive[C Drive] inside a folder named php [ie. C:\php].
    • Step 3: Now we have to add the folder [C:\php] to the Environment Variable Path so that it becomes accessible from the command line. To do so, we have to right click on My Computer or This PC icon, then Choose Properties from the context menu. Then click the Advanced system settings link, and then click Environment Variables. In the section System Variables, we have to find the PATH environment variable and then select and Edit it. If the PATH environment variable does not exist, we have to click New. In the Edit System Variable [or New System Variable] window, we have to specify the value of the PATH environment variable [C:\php or the location of our extracted php files]. After that, we have to click OK and close all remaining windows by clicking OK.

    PHP Installation for Linux Users:

    • Linux users can install php using the following command.
      apt-get install php5-common libapache2-mod-php5 php5-cli

      It will install php with apache server. For more information click here.

      • PHP Installation for Mac Users:

        • Mac users can install php using the following command.
          curl -s //php-osx.liip.ch/install.sh | bash -s 7.3

          It will install php in your system. For more information click here.

          • After installation of PHP, we are ready to run PHP code through command line. You just follow the steps to run PHP program using command line.

            • Open terminal or command line window.
            • Goto the specified folder or directory where php files are present.
            • Then we can run php code using the following command:
              php file_name.php

            • We can also start server for testing the php code using the command line by the following command:
              php -S localhost:port -t your_folder/

            Note: While using the PHP built-in server, the name of the PHP file inside the root folder must be index.php, and all other PHP files can be hyperlinked through the main index page.

            PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.

    Executing PHP files

    There are three different ways of supplying the CLI SAPI with PHP code to be executed:

    1. Tell PHP to execute a certain file.

      $ php my_script.php
      
      $ php -f my_script.php
      

      Both ways [whether using the -f switch or not] execute the file my_script.php. Note that there is no restriction on which files can be executed; in particular, the filename is not required have a .php extension.

    2. Pass the PHP code to execute directly on the command line.

      $ php -r 'print_r[get_defined_constants[]];'
      

      Special care has to be taken with regard to shell variable substitution and usage of quotes.

      Note:

      Read the example carefully: there are no beginning or ending tags! The -r switch simply does not need them, and using them will lead to a parse error.

    3. Provide the PHP code to execute via standard input [stdin].

      This gives the powerful ability to create PHP code dynamically and feed it to the binary, as shown in this [fictional] example:

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

    You cannot combine any of the three ways to execute code.

    As with every shell application, the PHP binary accepts a number of arguments; however, the PHP script can also receive further arguments. The number of arguments that can be passed to your script is not limited by PHP [and although the shell has a limit to the number of characters which can be passed, this is not in general likely to be hit]. The arguments passed to the script are available in the global array $argv. The first index [zero] always contains the name of the script as called from the command line. Note that, if the code is executed in-line using the command line switch -r, the value of $argv[0] will be "Standard input code"; prior to PHP 7.2.0, it was a dash ["-"] instead. The same is true if the code is executed via a pipe from STDIN.

    A second global variable, $argc, contains the number of elements in the $argv array [not the number of arguments passed to the script].

    As long as the arguments to be passed to the script do not start with the - character, there's nothing special to watch out for. Passing an argument to the script which starts with a - will cause trouble because the PHP interpreter thinks it has to handle it itself, even before executing the script. To prevent this, use the argument list separator --. After this separator has been parsed by PHP, every following argument is passed untouched to the script.

    # This will not execute the given code but will show the PHP usage
    $ php -r 'var_dump[$argv];' -h
    Usage: php [options] [-f]  [args...]
    [...]
    
    # This will pass the '-h' argument to the script and prevent PHP from showing its usage
    $ php -r 'var_dump[$argv];' -- -h
    array[2] {
      [0]=>
      string[1] "-"
      [1]=>
      string[2] "-h"
    }
    

    However, on Unix systems there's another way of using PHP for shell scripting: make the first line of the script start with #!/usr/bin/php [or whatever the path to your PHP CLI binary is if different]. The rest of the file should contain normal PHP code within the usual PHP starting and end tags. Once the execution attributes of the file are set appropriately [e.g. chmod +x test], the script can be executed like any other shell or perl script:

    Example #1 Execute PHP script as shell script

    #!/usr/bin/php

    Assuming this file is named test in the current directory, it is now possible to do the following:

    $ chmod +x test
    $ ./test -h -- foo
    array[4] {
      [0]=>
      string[6] "./test"
      [1]=>
      string[2] "-h"
      [2]=>
      string[2] "--"
      [3]=>
      string[3] "foo"
    }
    

    As can be seen, in this case no special care needs to be taken when passing parameters starting with -.

    The PHP executable can be used to run PHP scripts absolutely independent of the web server. On Unix systems, the special #! [or "shebang"] first line should be added to PHP scripts so that the system can automatically tell which program should run the script. On Windows platforms, it's possible to associate php.exe with the double click option of the .php extension, or a batch file can be created to run scripts through PHP. The special shebang first line for Unix does no harm on Windows [as it's formatted as a PHP comment], so cross platform programs can be written by including it. A simple example of writing a command line PHP program is shown below.

    Example #2 Script intended to be run from command line [script.php]

    #!/usr/bin/php


    This is a command line PHP script with one option.

      Usage:
       

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

    The script above includes the Unix shebang first line to indicate that this file should be run by PHP. We are working with a CLI version here, so no HTTP headers will be output.

    The program first checks that there is the required one argument [in addition to the script name, which is also counted]. If not, or if the argument was --help, -help, -h or -?, the help message is printed out, using $argv[0] to dynamically print the script name as typed on the command line. Otherwise, the argument is echoed out exactly as received.

    To run the above script on Unix, it must be made executable, and called simply as script.php echothis or script.php -h. On Windows, a batch file similar to the following can be created for this task:

    Example #3 Batch file to run a command line PHP script [script.bat]

    @echo OFF
    "C:\php\php.exe" script.php %*

    Assuming the above program is named script.php, and the CLI php.exe is in C:\php\php.exe, this batch file will run it, passing on all appended options: script.bat echothis or script.bat -h.

    See also the Readline extension documentation for more functions which can be used to enhance command line applications in PHP.

    On Windows, PHP can be configured to run without the need to supply the C:\php\php.exe or the .php extension, as described in Command Line PHP on Microsoft Windows.

    Note:

    On Windows it is recommended to run PHP under an actual user account. When running under a network service certain operations will fail, because "No mapping between account names and security IDs was done".

    php at richardneill dot org

    9 years ago

    On Linux, the shebang [#!] line is parsed by the kernel into at most two parts.
    For example:

    1:  #!/usr/bin/php
    2:  #!/usr/bin/env  php
    3:  #!/usr/bin/php -n
    4:  #!/usr/bin/php -ddisplay_errors=E_ALL
    5:  #!/usr/bin/php -n -ddisplay_errors=E_ALL

    1. is the standard way to start a script. [compare "#!/bin/bash".]

    2. uses "env" to find where PHP is installed: it might be elsewhere in the $PATH, such as /usr/local/bin.

    3. if you don't need to use env, you can pass ONE parameter here. For example, to ignore the system's PHP.ini, and go with the defaults, use "-n". [See "man php".]

    4.  or, you can set exactly one configuration variable. I recommend this one, because display_errors actually takes effect if it is set here. Otherwise, the only place you can enable it is system-wide in php.ini. If you try to use ini_set[] in your script itself, it's too late: if your script has a parse error, it will silently die.

    5. This will not [as of 2013] work on Linux. It acts as if the whole string, "-n -ddisplay_errors=E_ALL" were a single argument. But in BSD, the shebang line can take more than 2 arguments, and so it may work as intended.

    Summary: use [2] for maximum portability, and [4] for maximum debugging.

    email at alexander-bombis dot de

    1 year ago

    For Windows:

    After the years I also have the fact that I have to use double quotation marks after php -r on Windows shell.

    But in the Powershell you can use single or double quotation!

    gabriel at figdice dot org

    5 years ago

    Regarding shebang:

    In both Linux and Windows, when you execute a script in CLI with:

        php script.php

    then PHP will ignore the very first line of your script if it starts with:

        #!

    So, this line is not only absorbed by the kernel when the script file is executable, but it is also ignored by the PHP engine itself.

    However, the engine will NOT ignore the first #! line of any included files withing your "outer" script.php.
    Any "shebang" line in an included script, will result in simply outputting the line to STDOUT, just as any other text residing outside a block.

    david at frankieandshadow dot com

    6 years ago

    A gotcha when using #!/usr/bin/php at the start of the file as noted above:

    if you originally edited the file on Windows and then attempt to use it on Unix, it won't work because the #! line requires a Unix line ending. Bash gives you the following error message if it has DOS line endings:
    "bash: /usr/local/bin/wpreplace.php: /usr/bin/php^M: bad interpreter: No such file or directory"

    [In Emacs I used "CTRL-X ENTER f" then type "unix" and ENTER to convert]

    spencer at aninternetpresence dot net

    11 years ago

    If you are running the CLI on Windows and use the "-r" option, be sure to enclose your PHP code in double [not single] quotes. Otherwise, your code will not run.

    What is the process of running PHP script?

    To locally run a PHP Script:.
    Click the arrow next to the Run button. on the toolbar and select Run Configurations -or- go to Run | Run Configurations. A Run dialog will open..
    Double-click the PHP Script option to create a new run configuration..

    How write and run PHP program?

    Step 1: First of all, open the Apache Friends website and download XAMPP for Windows, and install it. Step 2: Start the XAMPP Program Control Panel. Click on the “Start” button next to the “Apache” to start your Apache Web Server. Also, start “MySQL” if your PHP programs depend on a MySQL database to run.

    How do you write PHP script?

    How to create a PHP script.
    Line 1 – This tag tells the server that you are writing PHP code..
    Line 2 – You can use the echo function to print out a string of text, this will be displayed back when the script is run..
    Line 3 – This tag tells the server that you have stopped writing PHP code..

    What is a PHP script?

    PHP is a server side scripting language. that is used to develop Static websites or Dynamic websites or Web applications. PHP stands for Hypertext Pre-processor, that earlier stood for Personal Home Pages. PHP scripts can only be interpreted on a server that has PHP installed.

    Chủ Đề