How to run PHP script without a web server

The PHP interpreter has become an essential part of almost every web server. The vast majority of web applications are written in PHP. Therefore, many people associate PHP technology with the web environment, with the environment of the web server. But in reality, you can run PHP scripts without a web browser. We are not talking about programs specially created as web applications, such as WordPress, phpMyAdmin, guest book scripts, forums, etc. Such scripts were specially created to work in a web server environment and to output the results to a web browser. It is unlikely that you will be able to fully work with them in the command line. We are talking about PHP console programs that can perform various functions, not necessarily related to web services. In fact, PHP is a very flexible language with a good set of classes and you can write a console program on it for any function. Or the core of the program (the so-called back-end), which will be accessed by the graphical user interface.

Also, launching PHP scripts in the console is convenient for language learners. Although someone may disagree with this. When outputting results to the console, as well as when passing arguments to a script, you don't need to pay attention to HTML. But if you study PHP to create web applications and online services, then you still have to finish learning the specifics of passing arguments from a web browser (in the server environment), as well as HTML in general, since all script output will need to be formatted for users' browsers.

How to run PHP script on Linux command line

You must have PHP installed, fortunately on Linux the PHP interpreter is very easy to install, and on some distributions it is present by default. If you don't have it yet, then install it with one of the following commands.

On Debian, Kali Linux, Linux Mint, Ubuntu:

sudo apt install php

On Arch Linux, BlackArch:

sudo pacman -S php

How to install a web server in Linux Mint and Ubuntu is described here, in Kali Linux it is already installed, how to start it here.

Otherwise, the launch of scripts in the console, including the launch options, are identical in Linux and Windows.

How to run PHP script on Windows command line

If you are familiar with running console programs in Windows or at least in Linux, then everything is quite simple for you – programs are launched everywhere in about the same way. But let's start with the basics for beginners.

If you want not only the ability to run PHP from the command line, but also a full-fledged Apache + PHP + MySQL web server on Windows, then complete the installation according to this article.

To run PHP on the command line, you do not need to install a web server, just download and unpack the archive with the PHP interpreter.

Let's start by downloading the latest PHP version for Windows from the official website:

There are several options that differ:

  • Version (e.g. 8.0, 7.4, 7.3)
  • Computer architecture, (x64 and x86)
  • Thread Safe or Non Thread Safe

Choose the latest version, between x64 and x86 choose the same version as your webserver. That is, if your Apache is 64-bit, then PHP must be 64-bit as well. Always choose ‘Thread Safe’ version.

There are two links for each file:

  • Zip
  • Debug Pack

Choose Zip because the debug package is only for those who really know why they need it. This does not mean debugging PHP scripts, but debugging the PHP interpreter itself.

If you often run PHP scripts from the Windows command line, it is highly recommended to To add PHP path to %PATH% environment variable on Windows. This eliminates the need to specify the full path to the php.exe file every time.

Now that PHP is installed and the path to php.exe has been added to the Windows environment variable, open a command prompt by pressing the Win+x key combination and select Windows PowerShell.

To check what works fine, look at the PHP help:

php -h

In fact, we are running the php.exe file, but the extension can be dropped. That is, the previous entry is equivalent to

php.exe -h

Help and options for running PHP scripts on the command line

The help contains command line options for various variants for running .php files on the command line, so I will give its translation in full.


php [options] [-f]  [--] [args...]
php [options] -r  [--] [args...]
php [options] [-B ] -R  [-E ] [--] [args...]
php [options] [-B ] -F  [-E ] [--] [args...]
php [options] -S : [-t docroot] [router]
php [options] -- [args...]
php [options] -a

As you can see, there are many launch options. If you don't quite understand what it means, don't worry. At the beginning, we will get acquainted with the meaning of the options, study, so to speak, the materiel, and then proceed with specific examples that will bring final clarity.


  -a               Run as interactive shell
  -c <path>|<file> Look for php.ini file in this directory
  -n               No configuration (ini) files will be used
  -d foo[=bar]     Define INI entry foo with value 'bar'
  -e               Generate extended information for debugger/profiler
  -f <file>        Parse and execute <file>.
  -h               This help
  -i               PHP information
  -l               Syntax check only (lint)
  -m               Show compiled in modules
  -r <code>        Run PHP <code> without using script tags <?..?>
  -B <begin_code>  Run PHP <begin_code> before processing input lines
  -R <code>        Run PHP <code> for every input line
  -F <file>        Parse and execute <file> for every input line
  -E <end_code>    Run PHP <end_code> after processing all input lines
  -H               Hide any passed arguments from external tools.
  -S <addr>:<port> Run with built-in web server.
  -t <docroot>     Specify document root <docroot> for built-in web server.
  -s               Output HTML syntax highlighted source.
  -v               Version number
  -w               Output source with stripped comments and whitespace.
  -z <file>        Load Zend extension <file>.

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

  --ini            Show configuration file names

  --rf <name>      Show information about function <name>.
  --rc <name>      Show information about class <name>.
  --re <name>      Show information about extension <name>.
  --rz <name>      Show information about Zend extension <name>.
  --ri <name>      Show configuration for extension <name>.

How to run .php script on Windows and Linux command line

The following command is used to run the .php file in the Windows console:

php -f path\to\file.php

The -f option can be skipped, that is, the previous and next commands are the same:

php path\to\file.php

I created a test file which is located in the path C:\Users\Alex\Documents\PHP\test.php then I can run it in PHP like so:

php -f C:\Users\Alex\Documents\PHP\test.php

or like this:

php C:\Users\Alex\Documents\PHP\test.php

How to pass arguments to a PHP script on the command line

To pass arguments to the script, list them after the filename, separated by a space. If the arguments themselves contain spaces or other characters that are special to the command line shell, then enclose those arguments in single or double quotes.

php path\to\file.php 'arg1' 'arg2' 'arg3' 'arg_n'

An example of running a PHP script with three arguments:

php C:\Users\Alex\Documents\PHP\test.php 'Alex' '' 'Admin'

How to access arguments in a PHP script

The arguments passed are contained in the $argv array. Moreover, the ordinal number of the argument corresponds to the number in the array. That is, the first argument will be placed in $argv[1], the second in $argv[2], and so on.

The very first element of the array named $argv[0] contains the full path to the script to run.

The content of the test.php file:


echo 'Name: ' . $argv[1] . PHP_EOL;
echo 'Web site: ' . $argv[2] . PHP_EOL;
echo 'Status: ' . $argv[3] . PHP_EOL;

Let's run it and pass three arguments to the script:

php C:\Users\Alex\Documents\PHP\test.php 'Alex' '' 'Admin'

How to get data from user in the console in PHP

Thanks to the passed arguments, the script can perform actions not only with the data written in it, but also with other values specified when the script was run.

By the way, when working in a web server environment, that is, when a PHP script performs tasks for a website, the ability to pass arguments to it is implemented using the HTTP GET and POST methods. These arguments are passed before starting the script, and after starting the PHP script, new data cannot be sent – you need to wait for the program to finish running, and, if necessary, run it again with new data.

While the script is running, it may be necessary to enter new data; in the console, this is achieved using a prompt, into which the user can enter a value and press Enter to pass it to the script. In the context of a website, there is no such possibility – to transfer data already during the execution of the script. That is, the console launch of PHP scripts with arguments is not only easier (no need to fiddle with an HTML form), but even more flexible.

PHP uses the readline function to query the user.

This feature works the same on both Windows and Linux. Moreover, on Linux, it has the interactive capabilities of Bash, for example, it saves the input history, to which you can return using the arrows. On Windows, this feature has appeared since PHP 7.1.

If you really need to, you can configure the auto-completion of the input data. All GNU Readline features are covered here. I will only touch on readline, which reads the line entered by the user. With this function, you can specify one optional argument – a string that will be shown to the user at the prompt.

An example of a PHP console script that asks the user for data at a command line prompt:


$len_min = readline("The minimum number of characters in a password is: ");
$len_max = readline("Maximum number of characters in a password: ");
$base = readline("Password base (0 - digits; 1 - lowercase letters; 2 - uppercase letters): ");

echo "Received initial data: \r\nPassword length from $len_min to $len_max characters ";
switch ($base) {
	case 0:
		echo "and the base of the password is in lowercase digits.";
	case 1:
		echo "and the base of the password is in lowercase letters.";
	case 2:
		echo "and the base of the password is in uppercase letters.";

Checking the syntax of a PHP script on the command line

With the -l option, the syntax will be checked, that is, whether the rules of the PHP code are violated, but the script file itself will not be executed:


php -l C:\Users\Alex\Documents\PHP\test.php
No syntax errors detected in C:\Users\Alex\Documents\PHP\test.php

Or if there are errors in the file:

php -l C:\Users\Alex\Documents\PHP\test.php
PHP Parse error:  syntax error, unexpected end of file in C:\Users\Alex\Documents\PHP\test.php on line 20

Parse error: syntax error, unexpected end of file in C:\Users\Alex\Documents\PHP\test.php on line 20
Errors parsing C:\Users\Alex\Documents\PHP\test.php

How to execute PHP commands interactively

If you need it, then you can work with the PHP interpreter interactively, entering the code line by line. In this case, the code is executed after pressing the Enter button, but the values of the variables are saved within one session. That is, you can assign a value to a variable and then use it in other lines.

To run an interactive shell:

php -a

How to run individual PHP commands

Use the -r option to run individual commands:

php -r 'echo 2**100;'

How to start PHP's built-in web server

PHP has its own web server! If you really need it, you can generally do without third-party servers for some specific tasks.

The options are as follows:

  -S <addr>:<port> Run with built-in web server.
  -t <docroot>     Specify document root <docroot> for built-in web server.

Let's say I want to set as the listening IP address, 84 as the listening port, the root folder of the web server documents is located in C:\Users\Alex\Documents\PHP\, then the launch command is as follows:

php -S -t C:\Users\Alex\Documents\PHP\

In this folder I have a test_2.php file with the following content:


print ("<table border=\"1\">

<td>Remote IP</td>
<td>" . $_SERVER ['REMOTE_ADDR'] . "</td>

<td>Server software</td>
<td>" . $_SERVER ['SERVER_SOFTWARE'] . "</td>

<td>" . $_SERVER ['HTTP_ACCEPT_LANGUAGE'] . "</td>

<td>" . $_SERVER ['HTTP_REFERER'] . "</td>

<td>Browser (or whatever)</td>
<td>" . $_SERVER ['HTTP_USER_AGENT'] . "</td>

<td>Request Method</td>
<td>" . $_SERVER ['REQUEST_METHOD'] . "</td>

<td>Request Time</td>
<td>" . $_SERVER ['REQUEST_TIME'] . "</td>

<td>Query String</td>
<td>" . $_SERVER ['QUERY_STRING'] . "</td>

<td>Request header</td>
<td>" . $_SERVER ['HTTP_ACCEPT'] . "</td>

<td>Request Address</td>
<td>" . $_SERVER ['REQUEST_URI'] . "</td>

<td>Server name</td>
<td>" . $_SERVER ['SERVER_NAME'] . "</td>


I open the address in a web browser

In the console I see:

In the web browser:

It would be possible to try to run WordPress in the built-in web server, just out of interest.

Getting help from the command line

To get help about PHP functions directly on the command line, use the --rf option.

For example, I want to know about readline:

php --rf readline
Function [  function readline ] {

  - Parameters [1] {
    Parameter #0 [  $prompt ]

Well, something like that… but what did you want – it's a console.

Readfile info:

php --rf readfile
Function [  function readfile ] {

  - Parameters [3] {
    Parameter #0 [  $filename ]
    Parameter #1 [  $flags ]
    Parameter #2 [  $context ]

As far as I understand, in the Parameters line, the number of function arguments is written in curly braces, the required line means that the argument is mandatory, and the optional line means that the argument is not mandatory. You can sometimes guess the function of arguments by their name, for example, $filename. There is apparently no information about what action the function performs.

Developer options

If you really write and debug code, including for websites, then the following options will come in handy:

  -s               Output HTML syntax highlighted source.
  -v               Version number

How to print information about PHP

The following three options are available to display PHP information:

  -i               PHP information
  -v               Version number
  --ini            Show configuration file names

The -i option is the equivalent to phpinfo, but for the console.

PHP cannot save file even with sufficient write permissions

In fact, this can happen not only when running PHP scripts from the command line, but also when running a script on a web server. But when run in the console, there are more conditions for getting this problem: PHP script does not save the file to a folder with write permissions for anyone (777).

This behavior may seem inexplicable if you are not aware of the open_basedir directive in the main php.ini configuration file. This directive restricts all file operations to the folders specified with it. Example:

open_basedir = /srv/http/:/etc/webapps/:/usr/share/webapps/:/tmp/:

This entry means that the PHP script can write files to the /srv/http/ folder, as well as to the /etc/webapps/, /usr/share/webapps/ and /tmp/ folders.

Moreover, if the open_basedir directive is not configured at all (the line with it, for example, is commented out), then PHP can write to any folder if the current user has sufficient write permissions.

When working in the PHP console, the script may try to save files, for example, to the current folder – if this folder is not specified in open_basedir, but the open_basedir directive itself is configured, then the described problem will arise: PHP will not be able to write files even to a folder open to everyone.

There are several options to get rid of this error:

  • add the folder where you want to save the file to the open_basedir list
  • select the folder already specified in open_basedir to save
  • start the PHP interpreter without reading the settings from the configuration files (in this case, the open_basedir directive will not be taken into account, as well as all other configurations in general

To run a PHP script without taking into account the php.ini file settings, use the -n option, for example:

php -n script.php

By the way, to find out which configuration files are taken into account when PHP is running, run the following command:

php --ini

Output example:

Configuration File (php.ini) Path: /etc/php
Loaded Configuration File:         /etc/php/php.ini
Scan for additional .ini files in: /etc/php/conf.d
Additional .ini files parsed:      (none)


Running PHP scripts on the command line is an alternative to running them through a web server. Working in the console can be convenient when learning the PHP programming language or for debugging certain functions, even if in the future these functions and scripts will work on the web server.

A PHP script can be an alternative to a Bash script, especially if you need to use a DBMS (MySQL, SQLite) – which is difficult to work with through Bash, or to use PHP's capabilities for working with text in XML, JSON markup – which is also not very convenient in Bash…

In any case, you need to be aware of this possibility, since some programs, especially exploits, are PHP scripts designed to be run on the command line with arguments.

Recommended for you:

Leave a Reply

Your email address will not be published.