Introduction to PHP
PHP is a scripting language designed for building websites. It runs on the server: when someone visits a PHP page, the server runs the PHP code and sends back the resulting HTML. PHP powers WordPress, which alone runs a large share of all websites, plus Wikipedia, Facebook's early versions and countless online shops.
How PHP works
Diagram
Browser asks for page.php
→ server runs the PHP code
→ PHP produces HTML
→ the browser receives plain HTML (never the PHP source)Built with PHP
| Project | What it is |
|---|---|
| the site builder behind a large share of all websites | |
| a popular framework for web apps | |
| a framework whose components many projects reuse | |
| PHP's package manager, for adding libraries |
Your first script
PHP
<?php
echo "Hello, PHP!\n";
echo "Today's lucky number is " . rand(1, 100) . "\n";- PHP code goes between
<?phpand?>(the closing tag can be left off when a file is pure PHP). echooutputs text..joins strings.- Statements end with a semicolon.
PHP mixed with HTML
PHP was built to sit inside HTML pages:
PHP
<h1>Welcome</h1>
<p>The year is <?php echo date("Y"); ?>.</p>
<ul>
<?php foreach (["Python", "PHP", "SQL"] as $lang): ?>
<li><?php echo $lang; ?></li>
<?php endforeach; ?>
</ul>Run it: the output is plain HTML, which the playground also renders in its Preview tab.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.