Skip to main content

🛠ïļ Lesson 2: Setting Up Your Environment

Before writing PHP code, you need a working server environment. In this lesson, you'll verify your LAMP stack, configure Apache to serve PHP files, and run your very first PHP script.

ðŸŽŊ Learning Objectives

By the end of this lesson, you will be able to:

  • Verify that Apache, PHP, and MySQL are installed and running on your system
  • Create and view a phpinfo() page to confirm PHP configuration
  • Understand the Apache document root and how PHP files are served
  • Write and run your first PHP script in the browser
  • Set up a project folder for this course

Estimated Time: 45 minutes

Prerequisites: Lesson 1 (What Is PHP?), a working Ubuntu/WSL system

📋 Coming from the MySQL Course?

If you completed MySQL Foundations, you already have MySQL installed and running. This lesson will verify that and add the PHP layer on top. If you're starting fresh, don't worry — we'll walk through everything.

📑 In This Lesson

What Is a LAMP Stack?

A LAMP stack is a set of open-source software that works together to serve dynamic web pages. Each letter stands for one layer:

graph LR L["🐧 Linux
(Operating System)"] --> A["ðŸŠķ Apache
(Web Server)"] A --> M["🐎 MySQL
(Database)"] A --> P["🐘 PHP
(Language)"] style L fill:#f0f9ff,stroke:#0ea5e9,color:#0c4a6e style A fill:#fef3c7,stroke:#f59e0b,color:#78350f style M fill:#ecfdf5,stroke:#10b981,color:#064e3b style P fill:#f5f3ff,stroke:#8b5cf6,color:#4c1d95
Component Role What It Does for Us
Linux Operating System Ubuntu (or WSL on Windows) — the foundation everything runs on
Apache Web Server Listens for HTTP requests and serves files. When it sees a .php file, it hands it to PHP for processing.
MySQL Database Stores and retrieves structured data. PHP connects to MySQL to read/write data.
PHP Language Processes server-side logic, generates HTML, and acts as the glue between Apache and MySQL.

✅ Why LAMP?

The LAMP stack has been the most popular web development stack for decades. It's free, well-documented, runs on virtually every hosting provider, and powers millions of websites including WordPress. Learning LAMP gives you a rock-solid foundation for PHP development.

Step 1: Verify Your Stack

Let's check whether each component is already installed. Open your terminal (Ubuntu or WSL) and run these commands one at a time:

Check Apache

apache2 -v

You should see something like:

Expected Output:

Server version: Apache/2.4.x (Ubuntu)
Server built:   2024-xx-xx

Check PHP

php -v

Expected Output:

PHP 8.x.x (cli) (built: ...)
Copyright (c) The PHP Group
Zend Engine v4.x.x, Copyright (c) Zend Technologies
    with Zend OPcache v8.x.x, ...

Check MySQL

mysql --version

Expected Output:

mysql  Ver 8.x.x for Linux on x86_64 (MySQL Community Server - GPL)

Check the PHP-MySQL Extension

php -m | grep -i mysql

Expected Output:

mysqli
mysqlnd
pdo_mysql

The pdo_mysql extension is the one we'll use most in this course. If you see it listed, you're good.

📊 Scorecard

If all four checks pass, skip ahead to Step 3: The Apache Document Root. If anything is missing, continue to the next section.

Step 2: Install Anything Missing

First, update your package list:

sudo apt update

Install Apache (if missing)

sudo apt install apache2 -y

Install PHP and Common Extensions

sudo apt install php libapache2-mod-php php-mysql php-cli php-common -y

This installs:

  • php — The PHP language itself
  • libapache2-mod-php — The Apache module that lets Apache process PHP files
  • php-mysql — MySQL/PDO extensions for database access
  • php-cli — Command-line PHP (for running scripts from the terminal)
  • php-common — Common PHP modules

Install MySQL (if missing)

If you completed the MySQL Foundations course, you already have this. Otherwise:

sudo apt install mysql-server -y
sudo mysql_secure_installation

Start and Enable Services

# Start Apache
sudo service apache2 start

# Start MySQL
sudo service mysql start

# Verify both are running
sudo service apache2 status
sudo service mysql status

⚠ïļ WSL Users: Services Don't Auto-Start

On WSL (Windows Subsystem for Linux), services don't start automatically when you open your terminal. You'll need to run sudo service apache2 start and sudo service mysql start each time you open a new WSL session. Consider adding these to your ~/.bashrc file:

# Add to ~/.bashrc for auto-start (optional)
sudo service apache2 start 2>/dev/null
sudo service mysql start 2>/dev/null

Verify Apache Is Serving Pages

Open your browser and navigate to:

http://localhost

You should see the Apache2 Ubuntu Default Page — a page that says "It works!" This confirms Apache is running and serving files.

Step 3: The Apache Document Root

When Apache serves a web page, it looks for files in a specific directory called the document root. On Ubuntu, the default document root is:

/var/www/html

Any file you place in this directory becomes accessible via http://localhost/filename. This is where your PHP files need to live for Apache to serve them.

graph LR A["Browser requests
http://localhost/hello.php"] --> B["Apache looks in
/var/www/html/hello.php"] B --> C["PHP processes
the file"] C --> D["HTML sent back
to browser"] style A fill:#f0f9ff,stroke:#0ea5e9,color:#0c4a6e style B fill:#fef3c7,stroke:#f59e0b,color:#78350f style C fill:#f5f3ff,stroke:#8b5cf6,color:#4c1d95 style D fill:#ecfdf5,stroke:#10b981,color:#064e3b

Understanding File Permissions

The /var/www/html directory is owned by root, so you'll need sudo to create files there — or you can change ownership to your user for development purposes:

# Option A: Use sudo for each file (safe but tedious)
sudo nano /var/www/html/test.php

# Option B: Change ownership for development (recommended for local dev)
sudo chown -R $USER:$USER /var/www/html
ðŸ’Ą Note: Option B makes your life easier during development. On a production server, you'd keep stricter permissions — but for learning on your local machine, this is perfectly fine.

Verify PHP Is Connected to Apache

Apache needs to know how to handle .php files. This is usually configured automatically when you install libapache2-mod-php, but let's verify:

# Check if the PHP module is enabled
apache2ctl -M | grep php

Expected Output:

 php8_module (shared)

If you see php8_module (or similar), Apache knows how to process PHP files. If not, enable it:

sudo a2enmod php8.3    # Replace 8.3 with your PHP version
sudo service apache2 restart

Step 4: Your First PHP File — phpinfo()

The classic first step with any PHP installation is creating a phpinfo() page. This built-in function displays everything about your PHP configuration — version, loaded extensions, server settings, and more.

Create the File

# Navigate to the document root
cd /var/www/html

# Create the file
nano info.php

Type this single line of PHP:

<?php phpinfo(); ?>

Save and exit (Ctrl+O, Enter, Ctrl+X in nano).

View It in Your Browser

Open your browser and go to:

http://localhost/info.php

You should see a large, detailed page showing your entire PHP configuration. This page is incredibly useful for debugging.

What to Look For

Section What to Check
PHP Version Should say 8.x at the top of the page
Server API Should say Apache 2.0 Handler — confirms PHP is running through Apache
Loaded Configuration File Shows the path to php.ini — the main PHP config file
PDO drivers Scroll down to the PDO section — should list mysql
mysqli Should have its own section confirming the MySQL extension is loaded

⚠ïļ Security Warning

Delete info.php on any public-facing server! The phpinfo() page reveals detailed information about your server configuration that attackers can use. It's fine for local development, but never leave it on a live site.

# When you're done inspecting, delete it on production servers:
rm /var/www/html/info.php

Step 5: Hello, PHP!

Now let's write a proper "Hello, World!" script that demonstrates PHP in action — mixing PHP with HTML, just like you'll do throughout this course.

Create the File

nano /var/www/html/hello.php

Write the Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello PHP!</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 50px auto;
            padding: 20px;
            background: #f8f9fa;
        }
        .card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            margin: 15px 0;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        h1 { color: #7B68EE; }
        code { background: #e9ecef; padding: 2px 6px; border-radius: 3px; }
    </style>
</head>
<body>
    <h1>🐘 Hello, PHP!</h1>

    <div class="card">
        <h2>Server Information</h2>
        <p><strong>PHP Version:</strong> <?php echo phpversion(); ?></p>
        <p><strong>Server Software:</strong> <?php echo $_SERVER['SERVER_SOFTWARE']; ?></p>
        <p><strong>Document Root:</strong> <?php echo $_SERVER['DOCUMENT_ROOT']; ?></p>
    </div>

    <div class="card">
        <h2>Dynamic Content</h2>
        <p><strong>Current Date:</strong> <?php echo date('l, F j, Y'); ?></p>
        <p><strong>Current Time:</strong> <?php echo date('g:i:s A'); ?></p>
        <p><strong>Timezone:</strong> <?php echo date_default_timezone_get(); ?></p>
    </div>

    <div class="card">
        <h2>PHP Can Do Math</h2>
        <?php
            $a = 42;
            $b = 17;
            $sum = $a + $b;
            $product = $a * $b;
        ?>
        <p><code><?php echo $a; ?> + <?php echo $b; ?> = <?php echo $sum; ?></code></p>
        <p><code><?php echo $a; ?> × <?php echo $b; ?> = <?php echo $product; ?></code></p>
    </div>

    <div class="card">
        <h2>Congratulations! 🎉</h2>
        <p>If you can see this page with real data above (not raw PHP code), your
           LAMP stack is working correctly. PHP is processing this file on the server
           and sending HTML to your browser.</p>
        <p><strong>Try this:</strong> Right-click the page and select "View Page Source."
           Notice that there's no PHP code — only the HTML output. That's server-side
           processing in action!</p>
    </div>
</body>
</html>

View It

Navigate to http://localhost/hello.php in your browser. You should see a styled page with real, dynamic data — your PHP version, today's date, the current time, and math results.

✅ The "View Source" Test

Right-click the page in your browser and select "View Page Source". You'll see only HTML — no <?php tags anywhere. This confirms that PHP processed the file on the server and sent clean HTML to your browser, exactly as we described in Lesson 1.

Understanding What Happened

<!-- This is PHP embedded in HTML -->
<p>PHP Version: <?php echo phpversion(); ?></p>

<!-- The browser receives: -->
<p>PHP Version: 8.3.6</p>

Key observations:

  • <?php ... ?> — The opening and closing PHP tags. Everything between them is PHP code.
  • echo — Outputs text (sends it to the HTML).
  • phpversion() — A built-in function that returns the PHP version string.
  • $_SERVER — A superglobal array with server/request information (we'll explore these in Module 5).
  • date() — Formats the current date/time. The letters in the format string control the output.
  • $a = 42; — Variables in PHP start with $. We'll cover this properly in the next lesson.

Step 6: Set Up Your Course Project Folder

Throughout this course, we'll build small projects and exercises. Let's create a dedicated folder inside the document root:

# Create the course folder
mkdir -p /var/www/html/php-foundations

# Create subfolders for organization
mkdir -p /var/www/html/php-foundations/exercises
mkdir -p /var/www/html/php-foundations/projects

Your file structure will look like this:

/var/www/html/
├── index.html          ← Apache default page
├── info.php            ← phpinfo() (delete on production)
├── hello.php           ← Your first PHP file
└── php-foundations/    ← Course work goes here
    ├── exercises/      ← Lesson exercises
    └── projects/       ← Mini projects (like the CRUD app)

Test It

Create a quick index file for your course folder:

nano /var/www/html/php-foundations/index.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PHP Foundations - Course Work</title>
</head>
<body>
    <h1>PHP Foundations — Course Work</h1>
    <p>Welcome! This folder contains exercises and projects
       from the PHP Foundations course.</p>
    <p>Server time: <?php echo date('Y-m-d H:i:s'); ?></p>
</body>
</html>

Visit http://localhost/php-foundations/ to confirm it works.

✅ Your Editor

While we used nano in the terminal for these examples, you can use any code editor you prefer — VS Code is an excellent choice. If you're on WSL, VS Code can connect directly to your WSL filesystem using the Remote - WSL extension, giving you a full IDE experience while your files live in Linux.

Troubleshooting Common Issues

"localhost" Shows Nothing or Refuses to Connect

Cause: Apache isn't running.

Fix:

sudo service apache2 start
# Then check status:
sudo service apache2 status

Browser Shows Raw PHP Code Instead of Output

Cause: Apache doesn't have the PHP module enabled.

Fix:

sudo apt install libapache2-mod-php -y
sudo a2enmod php8.3   # Adjust version number
sudo service apache2 restart

phpinfo() Page Doesn't Show pdo_mysql

Cause: The PHP-MySQL extension isn't installed.

Fix:

sudo apt install php-mysql -y
sudo service apache2 restart

"Permission Denied" When Creating Files

Cause: /var/www/html is owned by root.

Fix:

sudo chown -R $USER:$USER /var/www/html

Port 80 Is Already in Use

Cause: Another process (often IIS on Windows, or another web server) is using port 80.

Fix: Find and stop the conflicting process, or change Apache's port:

# Find what's using port 80
sudo lsof -i :80

# If on WSL and Windows IIS is the issue:
# Open Windows Services (services.msc) and stop "World Wide Web Publishing Service"

MySQL Won't Start

Cause: Various — often a permissions or socket issue on WSL.

Fix:

# Try starting with verbose output
sudo service mysql start
# Check the error log
sudo cat /var/log/mysql/error.log | tail -20

# Common WSL fix — create the run directory
sudo mkdir -p /var/run/mysqld
sudo chown mysql:mysql /var/run/mysqld
sudo service mysql start

Knowledge Check

ðŸŽŊ Quick Quiz

Question 1: What does "LAMP" stand for?

Question 2: What is the default Apache document root on Ubuntu?

Question 3: If your browser shows raw PHP code (like <?php echo "hello"; ?>) instead of output, what's most likely wrong?

Question 4: Why should you delete info.php (the phpinfo page) on a production server?

Summary

🎉 Key Takeaways

  • LAMP = Linux + Apache + MySQL + PHP — the classic open-source web stack
  • Apache serves files from /var/www/html — place your PHP files there for Apache to process them
  • phpinfo() displays your full PHP configuration — essential for debugging, but a security risk on public servers
  • PHP mixes with HTML — code inside <?php ... ?> is processed on the server; everything else is sent as-is
  • WSL tip: Start Apache and MySQL manually each session with sudo service apache2 start and sudo service mysql start

📋 Environment Checklist

Before moving on, make sure you can check off everything:

  • ☐ Apache is running (http://localhost loads a page)
  • ☐ PHP is installed (php -v shows version 8.x)
  • ☐ PHP works through Apache (http://localhost/info.php shows the phpinfo page)
  • ☐ MySQL is running (sudo service mysql status says active)
  • ☐ PDO MySQL extension is loaded (visible in phpinfo under PDO drivers)
  • ☐ http://localhost/hello.php displays dynamic content
  • ☐ Course folder exists at /var/www/html/php-foundations/

🚀 What's Next?

Your environment is ready! In Lesson 3: PHP Syntax Basics, we'll dive into the language itself — variables, data types, echo vs print, comments, and PHP's type system. This is where the real coding begins!

🎉 Congratulations!

Your LAMP stack is verified and your first PHP scripts are running. You're officially a PHP developer (in training)! 🐘