PHP for HTML and CSS Developers
If you can write an HTML form, you can make your first PHP page. Put a form and some PHP in one file, then submit your name and watch the server render a greeting in the same page.
Start with the form you already know
Section titled “Start with the form you already know”Create an empty folder called php-greeting. Inside it, save this form in a file named index.php.
<!doctype html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>PHP greeting</title></head><body> <main> <h1>PHP greeting</h1>
<form method="get" action="/"> <label for="name">Your name</label> <input type="text" id="name" name="name" required> <button type="submit">Say hello</button> </form> </main></body></html>Run these commands from inside the folder. If php -v fails, follow the PHP setup lesson.
php -vphp -S 127.0.0.1:8000Open the local greeting form in your browser. Enter Sam and submit the form. You should see ?name=Sam in the address bar. The form sends the name, which the next step turns into a greeting. This local example uses GET so you can see the submitted value in the URL. Use it for information you are comfortable putting in a URL. HTML forms and user input
Read the input with PHP
Section titled “Read the input with PHP”Add this block above <!doctype html> in index.php. Keep the existing HTML below it.
<?phpdeclare(strict_types=1);
$submittedName = $_GET['name'] ?? '';$name = is_string($submittedName) ? trim($submittedName) : '';?>PHP reads the form field by its HTML name attribute. The ?? '' default covers the first visit. is_string() checks that the field is text before trim() removes surrounding whitespace.
Add this block directly after </form>.
<?php if ($name !== ''): ?> <p>Hello, <?= htmlspecialchars($name, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') ?>!</p><?php endif; ?>The server executes the PHP between <?php and ?>. The shorter <?= tag prints a value into the HTML response. htmlspecialchars() escapes characters that have a special meaning in HTML, so the browser renders the name as text. PHP tags · HTML escaping in PHP
Try three inputs
Section titled “Try three inputs”- Visit the page without a query string. The form appears with an empty result area.
- Submit
Sam. Expect Hello, Sam! - Submit
A & B. Expect Hello, A & B! In your browser’s page source, the ampersand in the greeting is written as&.
Use your usual CSS to style the form and greeting. If you want to keep results between visits, try the PHP and SQLite reading list starter. Stop the local server with Ctrl+C when you are done.