Kodokon kodokon.com

PHP and the server: your first script

Discover what PHP is, start the built-in server with php -S, write your first script with echo, and mix PHP and HTML.

7 min · 3 questions

Open this lesson in Kodokon

PHP is a programming language: a set of writing rules that lets you give instructions to a computer. What makes it special is that PHP code runs on a server, meaning a program that receives requests from a browser (Chrome, Firefox…) and sends back web pages. When you visit a PHP site, the server runs the code, builds the page, then sends the result to the browser. Visitors never see the PHP code, only the page it produces. Before you start, check that PHP is installed on your machine by opening a terminal (the app that lets you type commands) and entering:

BASH
php -v
If a version number appears, PHP is ready.

Good news: you don't need to install any heavy software to get to work. PHP ships with a built-in development server, perfect for learning. Create an empty folder (for example my-site), move into it with the terminal, then run the command below. localhost refers to your own computer, and 8000 is the port, a kind of door number the server listens on.

BASH
php -S localhost:8000
Run this from the folder that holds your files.

Now create a file named index.php in this folder. A .php file is a script: a sequence of instructions run from top to bottom. PHP code always begins with the opening tag <?php. The echo statement sends text to the page that will be displayed. Every statement ends with a semicolon ;. Then open your browser at http://localhost:8000: your message appears!

PHP
<?php

echo "Hello, world!";
Contents of the index.php file.

PHP's real strength: it slips right in the middle of HTML. You write your HTML page as usual, and whenever you need a computed piece of content, you open a PHP block with <?php and close it with ?>. Here, the date() function returns today's date: the displayed page therefore changes every day, without you touching the file.

HTML
<!DOCTYPE html>
<html lang="en">
  <body>
    <h1>My first PHP page</h1>
    <p>Today is <?php echo date("d/m/Y"); ?>.</p>
  </body>
</html>
An index.php file can contain both HTML and PHP.

Knowledge check

Make sure you remember the key points of this lesson.

  1. Where is PHP code executed?
    • In the visitor's browser
    • On the server, before the page is sent
    • In the database
  2. What does the echo statement do?
    • It saves a value to a file
    • It sends text into the displayed page
    • It starts the PHP server
  3. What is the php -S localhost:8000 command for?
    • To install PHP on the computer
    • To check the installed PHP version
    • To start the built-in development server