Skip to content
Happy Programming Guide
Start learning
PHP

Introduction to PHP

What PHP is, how it differs from JavaScript, how a request becomes a page, and your first working script — with the syntax you need to read real code.

A pen and an open notebook ready for notes

PHP is a language for building web pages on the server. When someone visits a PHP page, the server runs your code, produces HTML, and sends that HTML to the browser — which never sees the PHP at all. That one sentence explains most of what makes PHP different from JavaScript, and it is the right place to start.

What happens when someone visits a PHP page#

  1. The browser requests index.php.
  2. The web server sees the .php extension and hands the file to PHP.
  3. PHP runs the code, which may query a database or read files.
  4. PHP produces HTML.
  5. The server sends that HTML back. The browser receives ordinary HTML.

View source on a PHP page and you will not see any PHP. It has already run and finished. That is the fundamental difference from JavaScript, which is sent to the browser and runs there.

PHP Browser JavaScript
Runs on the server the visitor’s device
Can read files and databases Yes No
Visitor can see the code No Yes
Can respond to a click Only by a new request Instantly
Safe place for secrets Yes Never

Your first script#

PHP
<?php
$name = "Ana";
$hour = (int) date("G");
$greeting = $hour < 12 ? "Good morning" : "Good afternoon";
?>
<!doctype html>
<html lang="en">
<body>
  <h1><?= htmlspecialchars($greeting) ?>, <?= htmlspecialchars($name) ?></h1>
</body>
</html>

Run it with PHP’s built-in server:

Terminal
php -S localhost:8000

Then open http://localhost:8000. No Apache, no configuration — enough for learning and local development.

<?= is shorthand for <?php echo. Note the htmlspecialchars around every value: that is what stops user-supplied text being interpreted as HTML, and it is a habit worth forming from your very first script.

The syntax#

PHP
<?php
// Variables always start with a dollar sign
$name = "Ana";
$age = 34;
$price = 12.99;
$isActive = true;
$nothing = null;

// Strings: double quotes interpolate, single quotes do not
echo "Hello $name";        // Hello Ana
echo 'Hello $name';        // Hello $name
echo "Total: {$price}";    // braces for clarity

// Concatenation uses a dot, not a plus
echo "Hello " . $name;

The dot for concatenation is the detail that catches people arriving from JavaScript or Python. "a" + "b" in PHP does not join strings.

Arrays#

PHP
<?php
$fruits = ["apple", "pear", "plum"];
echo $fruits[0];
echo count($fruits);

// Associative array - the workhorse of PHP
$person = [
    "name" => "Ana",
    "age"  => 34,
];

echo $person["name"];

foreach ($fruits as $fruit) {
    echo $fruit;
}

foreach ($person as $key => $value) {
    echo "$key: $value";
}

PHP has one array type that serves as both a list and a dictionary, which is unusual and very convenient.

Conditions and loops#

PHP
<?php
if ($score >= 80) {
    $grade = "A";
} elseif ($score >= 70) {
    $grade = "B";
} else {
    $grade = "F";
}

for ($i = 0; $i < 5; $i++) { echo $i; }

while ($n < 10) { $n++; }

// Alternative syntax, for mixing with HTML
if ($loggedIn): ?>
  <p>Welcome back</p>
<?php else: ?>
  <p>Please sign in</p>
<?php endif;

That last form is worth knowing. Inside templates it is far easier to read than braces scattered between HTML tags.

Functions#

PHP
<?php
function greet(string $name, string $greeting = "Hello"): string
{
    return "$greeting, $name!";
}

echo greet("Ana");
echo greet("Ana", "Good morning");

The type declarations are optional but strongly recommended. Add this at the top of each file and PHP enforces them strictly rather than converting silently:

PHP
<?php
declare(strict_types=1);

Superglobals#

PHP gives you a set of arrays that are available everywhere:

PHP
<?php
$_GET      // values from the query string
$_POST     // values from a submitted form
$_SESSION  // per-visitor storage across requests
$_COOKIE   // cookies sent by the browser
$_FILES    // uploaded files
$_SERVER   // request and server information
PHP
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $email = trim($_POST["email"] ?? "");

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "That does not look like an email address.";
    }
}

Sessions#

PHP
<?php
session_start();          // must come before any output

$_SESSION["user_id"] = 42;

if (isset($_SESSION["user_id"])) {
    echo "Signed in";
}

session_destroy();

HTTP forgets you between requests. Sessions are how a site remembers that you are logged in.

Databases#

PHP
<?php
$pdo = new PDO("mysql:host=localhost;dbname=shop;charset=utf8mb4", $user, $pass, [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

$stmt = $pdo->prepare("SELECT id, name FROM products WHERE price < ?");
$stmt->execute([20]);

foreach ($stmt as $row) {
    echo htmlspecialchars($row["name"]);
}

Use prepared statements from the very beginning. Building SQL by pasting variables into a string is the single most exploited mistake in PHP.

What PHP is used for#

A very large share of the web runs on it: WordPress, Drupal, Magento and a great many custom applications. Laravel and Symfony are mature, well-designed frameworks that handle routing, templating, database access and security for you.

The language’s poor reputation dates from PHP 4 and 5, which had inconsistent function names and unsafe defaults. Modern PHP has strict types, proper exceptions, an excellent package manager in Composer, and performance several times better than a decade ago. Much of the criticism you will read online is describing a version nobody should still be running.

Questions people ask#

Do I need Apache or nginx to learn PHP?

No. php -S localhost:8000 is enough for local development. Use a proper server for anything live.

Which PHP version should I use?

The newest version that still receives active support. Anything older than PHP 8 is missing years of language improvements and, more importantly, security fixes.

Should I learn a framework straight away?

Learn the basics first — requests, forms, sessions, PDO — then adopt Laravel or Symfony. Frameworks make much more sense once you have felt the problems they solve.

Is PHP still worth learning?

A large proportion of the web runs on it, WordPress alone accounts for an enormous number of sites, and there is steady demand for maintenance and new work. It is a practical choice, particularly for server-side web development.

Where to go next#

Working with forms in PHP, validated and safeRead next

Keep reading

PHP

PHP Performance Optimization

Where PHP applications actually spend their time, how to measure before you optimise, and the fixes that matter: OPcache, N+1 queries, indexes…

5 min read

PHP

Working with APIs in PHP

Call a REST API from PHP with cURL or Guzzle, handle JSON and errors properly, add authentication, and build a small API…

4 min read

PHP

PHP PDO Explained With Examples

PDO is the standard way to talk to a database from PHP. Connecting, prepared statements that stop SQL injection, fetching rows, transactions…

5 min read

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *