CodeMIRAI
0 XP

Introduction to PHP

2 min read 2 runnable examples Quiz included

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)
Browserasks for a pagerequestWeb serverPHP runs index.phpreads data, builds HTMLdatabaseHTML onlythe visitor never sees PHP code, only the HTML it printed
PHP runs on the server for every request. What reaches the browser is plain HTML.

Built with PHP

ProjectWhat it is
WordPressthe site builder behind a large share of all websites
Laravela popular framework for web apps
Symfonya framework whose components many projects reuse
ComposerPHP'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 <?php and ?> (the closing tag can be left off when a file is pure PHP).
  • echo outputs 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.