Skip to content

PHP vs HTML

HTML describes what a browser should display. PHP runs code that can generate that HTML before the browser receives it. When a site needs a personalised greeting, a list of database records or a form submission, PHP can calculate the result and return it as ordinary HTML.

TaskHTMLPHP
Describe a heading, link or formUse elements such as <h1>, <a> and <form>.Produce those elements in the response, often using a template.
Get inputA form names fields and describes how the browser submits them.Read the values received by the server and decide what to do.
Show data that changesThe browser renders the markup it receives.Query data or apply logic to generate different markup for different requests.
Run locallyA basic HTML file can open directly in a browser.Run a PHP server to execute a .php file.

Save this as index.html.

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Greeting form</title>
<form action="greeting.php" method="get">
<label for="name">Name</label>
<input id="name" name="name">
<button>Say hello</button>
</form>
</html>

Save this beside it as greeting.php.

<?php
$name = $_GET['name'] ?? '';
$name = is_string($name) ? trim($name) : '';
$name = htmlspecialchars($name === '' ? 'friend' : $name, ENT_QUOTES, 'UTF-8');
?>
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Greeting</title>
<p>Hello, <?= $name ?>!</p>
</html>

Run php -S 127.0.0.1:8000 and open http://127.0.0.1:8000/. Type Sam and submit to see Hello, Sam!. The form sends the name in the query string. PHP reads it, supplies a default for a blank name, and escapes the value before placing it in the HTML.

Learn enough HTML to build a readable page and an accessible form. Add PHP when the browser needs the server to save, retrieve, or calculate something. Once you can follow one request from form to PHP and back, server rendering and frameworks become easier to understand.