The different ways to run PHP

(Originally posted on my Portuguese blog at rberaldo.com.br)

PHP is widely known as a language for web application development. However, PHP is not limited to web development only. There are other ways to execute PHP, including running it in a command-line environment. There is even an interactive terminal for PHP.

Running PHP in a Web Server

This is the most common way. You can use servers like Apache, Nginx, IIS, and others. However, few are aware of the built-in PHP web server, available from PHP version 5.4.

To use the PHP internal server, create a file named index.php with this content:

<?php 
echo "Using the PHP internal server";

Save the file. Open the terminal and navigate to the directory where you saved index.php. Execute the following command:

php -S localhost:8000

This command will start the internal PHP server on port 8000. You can change the port if you already have another application running on that port or if you simply don’t like the number 8000. 😛

You will see this output:

PHP 5.6.6 Development Server started at Thu Mar 12 21:44:26 2015
Listening on http://localhost:8000
Document root is /tmp
Press Ctrl-C to quit.

Your server is now active. Access the URL http://localhost:8000, and you will see the message “Using the PHP internal server.” To stop the server, type “CTRL+C.”

I won’t go into details about running PHP in other web servers; there are various specific articles available on the internet.

Running PHP in Command Line

I hope you haven’t closed the terminal yet. In the same directory where your index.php script is located, execute this command:

php index.php

The message “Using the PHP command-line” will be displayed in the terminal. However, there is no line break at the end of it. Let’s edit the index.php file like this:

<?php 
echo "Using PHP in command line" . PHP_EOL;

The PHP_EOL constant corresponds to “End Of Line” and allows you to create portable scripts since the line break in Linux and Mac (and other Unix derivatives) is “\n,” and in Windows, it’s “\r\n.”

When you run the command php index.php again, the following result will appear in the terminal:

Using PHP in command line

Running PHP in the Interactive Terminal

PHP has an interactive terminal, which means it’s a terminal where each command you type is immediately executed. For example, when you run an echo command, the message is displayed on the screen.

To start the interactive terminal, enter the following command in the terminal:

php -a

You are now in the interactive terminal. You can enter any PHP command, and it will be executed. The semicolon ; is still required here. Don’t forget it!

Let’s look at some examples:

$ php -a
Interactive shell

php > echo "Hello World";
Hello World
php > $x = 2;
php > echo pow($x, 10);
1024
php > echo "without semicolon"
php > ;
without semicolon

If you forget the semicolon, you can place it on the following line without generating an error.

This interactive terminal is useful when you want to test a function without the need to create a separate script for it.

Related posts

6 Thoughts to “The different ways to run PHP”

  1. Sensacional o post! Eu particularmente no conhecia o terminal Interativo do PHP, vai me ajudar pacas nos testes rápidos 😛

    Para conteúdo de desenvolvimento web em geral acesse meu blog 🙂
    http://www.dorianneto.com.br/

  2. João Sérgio Pero Motta

    É possivel fazer com que num banco de dados mysql todos os dados preenchido com PHP sejam devidamente acentuados conforme charset utf8?

    1. Sim, é possível. Basta usar UTF-8 em toda a aplicação e não terá problemas.
      Veja este meu artigo: http://rberaldo.com.br/problemas-com-codificacao-acentos-nao-interpretados/

  3. Wadson

    Uma dúvida aqui: Criei as variáveis de ambiente e quando digito “php -S localhost:85” (estou usando a porta 85) a tela não aparece o que digitei. Como se não tivesse lendo o que digito no teclado. o que pode ser ? Vlw

    1. Olá. Não aparece nem o comando que você digitou? Se for isso, deve haver algum erro no temrinal/prompt.
      Se aparecer o comando mas não aparecer a saída dele, tente com uma porta maios que 1023. Portas baixas (1 a 1023) são reservadas para uso do Sistema Operacional.

      1. Wadson

        Valeu pela resposta. Depois da mensagem de clicar no ctrl + c pra sair o cursos pisca e nada do que eu digito aparece na tela.

Leave a Comment