Skip to main content

Course Progress

Loading...

Setting Up a Local Server Environment (XAMPP/MAMP)

Duration: 45 minutes
Module 1: Introduction to PHP

Learning Objectives

  • Master the concepts in this lesson
  • Apply knowledge through practice
  • Build practical skills
  • Prepare for next topics

Understanding Local Development Environments

Welcome to today's session on setting up a local server environment for PHP development! Before we dive into WordPress development, we need to establish our local workspace. This environment will allow you to build, test, and debug your PHP and WordPress projects without affecting a live website or requiring an internet connection.

Think of a local development environment as your personal laboratory. Just as a scientist needs a controlled space to conduct experiments before presenting findings to the world, web developers need a private server environment to build and test websites before deploying them to production.

Your Computer Local Development Environment Web Server PHP Interpreter Database Server WordPress Files Web Browser

Components of a Local Server Environment

To run PHP and WordPress locally, you need several interconnected components working together. Let's explore each one:

Web Server

The web server (usually Apache or Nginx) handles incoming requests and serves web pages. When you type "localhost" in your browser, the web server receives this request and processes it accordingly.

Analogy: Think of the web server as a restaurant host who receives guests (browser requests), finds them a table (processes the request), and ensures they're properly served (returns the appropriate response).

PHP Interpreter

The PHP interpreter processes PHP code and generates HTML output. The web server passes PHP files to this interpreter, which executes the code and returns the results.

Analogy: If the web server is the restaurant host, the PHP interpreter is the chef who takes raw ingredients (PHP code) and transforms them into delicious meals (HTML output) that can be served to the guests.

Database Server

WordPress and most PHP applications require a database to store content and settings. MySQL or MariaDB typically serves this purpose. The database server manages data storage, retrieval, and organization.

Analogy: The database server is like the pantry and refrigerator in our restaurant—it stores all the ingredients (data) in an organized manner so the chef (PHP) can quickly find and use them when preparing dishes (web pages).

phpMyAdmin

A web-based interface for managing MySQL databases. It allows you to create, modify, and delete databases and tables without using SQL commands directly.

Analogy: phpMyAdmin is like the inventory management system in our restaurant—it provides an intuitive interface for organizing the pantry (database) without needing to memorize complex inventory codes (SQL commands).

Browser Apache Web Server PHP Interpreter MySQL Database phpMyAdmin GUI for MySQL WordPress PHP Files

Local Development Solutions

There are several pre-packaged solutions that bundle all the necessary components for a local development environment. Let's explore the most popular options:

XAMPP

XAMPP (Cross-platform, Apache, MySQL, PHP, Perl) is one of the most popular local development environments, available for Windows, macOS, and Linux. It provides an all-in-one solution for PHP development.

Key Features

  • Cross-platform: Works on Windows, macOS, and Linux
  • Easy installation: Single installer packages all components
  • Control panel: Graphical interface to start/stop services
  • Multiple PHP versions: Can switch between PHP versions
  • phpMyAdmin: Included for database management
  • Free and open-source: No cost to use

Considerations

  • Default configuration might need adjustments for specific use cases
  • Security settings are relaxed by default (ideal for development but not production)
  • Some users report occasional stability issues with the MySQL service

MAMP

MAMP (macOS, Apache, MySQL, PHP) was originally designed for macOS but is now available for Windows as well. It offers a user-friendly interface and rapid setup.

Key Features

  • Intuitive interface: User-friendly control panel
  • Quick setup: Easy installation process
  • Multiple PHP versions: Easy switching between versions
  • Pro version available: Offers additional features (at a cost)
  • Virtual hosts: Easy setup for multiple projects

Considerations

  • Free version has limitations compared to MAMP Pro
  • MAMP Pro requires a paid license
  • May use more system resources than some alternatives

XAMPP vs MAMP: Which to Choose?

Feature XAMPP MAMP
Platforms Windows, macOS, Linux macOS, Windows
Price Free Free (Basic), Paid (Pro)
User Interface Good Excellent
Virtual Hosts Setup Manual configuration Easy UI in Pro version
Resource Usage Moderate Higher
PHP Version Switching Possible but requires more steps Simple toggle in interface

For our course, either solution will work well. We'll primarily focus on XAMPP due to its cross-platform nature and being completely free, but the concepts apply to either environment.

Other Solutions Worth Mentioning

  • WAMP Server: Windows-specific environment similar to XAMPP
  • Local by Flywheel: WordPress-focused local development environment
  • Laragon: Modern development environment for Windows with nice features for WordPress
  • Docker: Container-based approach for development environments (we'll cover this separately in our Docker sessions)

Installing XAMPP

Windows Installation

  1. Download XAMPP

    Visit Apache Friends website and download the latest version of XAMPP for Windows.

  2. Run the Installer

    Launch the downloaded installer (.exe file) and follow the prompts. You may receive security warnings about Windows Defender or antivirus software—these are normal as XAMPP needs to modify system settings.

  3. Select Components

    You can choose which components to install. For WordPress development, ensure Apache, MySQL, PHP, and phpMyAdmin are selected. Perl, FileZilla FTP, and others are optional.

  4. Choose Installation Folder

    The default is usually C:\xampp. If possible, keep this default path as it's simpler and avoids permission issues.

  5. Complete Installation

    The installer will extract files and set up XAMPP on your system. This may take several minutes.

  6. Launch Control Panel

    After installation, the XAMPP Control Panel should launch automatically. If not, you can find it in the start menu or installation directory.

Common Windows Installation Issues

  • Port Conflicts: If Apache or MySQL won't start, other applications might be using their ports (80 for Apache, 3306 for MySQL).

    Solution: Change ports in the configuration files or stop conflicting programs (Skype, IIS, other web servers).

  • Permission Issues: Windows security can sometimes block XAMPP functions.

    Solution: Run as administrator or adjust User Account Control settings.

macOS Installation

  1. Download XAMPP

    Visit Apache Friends website and download the latest version of XAMPP for macOS.

  2. Open the Installer

    Launch the downloaded .dmg file and follow the instructions to install XAMPP.

  3. Drag to Applications

    Drag the XAMPP folder to your Applications folder when prompted.

  4. Launch XAMPP

    Open the XAMPP application from your Applications folder. You may need to override Gatekeeper security by right-clicking the app and selecting "Open."

  5. Start Services

    Use the XAMPP Manager to start Apache and MySQL services.

Common macOS Installation Issues

  • Security Restrictions: macOS security features may block the installation.

    Solution: Adjust security settings in System Preferences > Security & Privacy, allowing applications from identified developers.

  • Port Conflicts: macOS may have built-in Apache or MySQL already running.

    Solution: Stop existing services or configure XAMPP to use different ports.

Linux Installation

  1. Download XAMPP

    Visit Apache Friends website and download the latest version of XAMPP for Linux.

  2. Make Installer Executable

    Open Terminal and navigate to your download folder. Make the installer executable with:
    chmod +x xampp-linux-x64-[version]-installer.run

  3. Run the Installer

    Execute the installer with:
    sudo ./xampp-linux-x64-[version]-installer.run

  4. Follow Setup Wizard

    Complete the installation by following the graphical installer.

  5. Launch XAMPP Control Panel

    Start the XAMPP control panel with:
    sudo /opt/lampp/manager-linux-x64.run

Common Linux Installation Issues

  • Permission Issues: Linux file permissions can cause problems.

    Solution: Set appropriate permissions for your web directory:
    sudo chmod 777 -R /opt/lampp/htdocs
    (Note: 777 permissions are not secure for production, but acceptable for local development)

  • Service Conflicts: Existing Apache or MySQL services may conflict.

    Solution: Stop existing services:
    sudo service apache2 stop
    sudo service mysql stop

Installing MAMP

macOS Installation

  1. Download MAMP

    Visit MAMP website and download MAMP for macOS (the free version is sufficient for our needs).

  2. Open the Installer

    Launch the downloaded .pkg file and follow the installation wizard.

  3. Complete Installation

    Drag the MAMP folder to your Applications folder when prompted.

  4. Launch MAMP

    Open MAMP from your Applications folder.

  5. Start Servers

    Click the "Start Servers" button to begin using MAMP.

Windows Installation

  1. Download MAMP

    Visit MAMP website and download MAMP for Windows.

  2. Run the Installer

    Launch the downloaded .exe file and follow the installation wizard.

  3. Choose Installation Location

    Select where you want to install MAMP (default is usually fine).

  4. Complete Installation

    Finish the installation process by following the remaining prompts.

  5. Launch MAMP

    Open MAMP from the Start menu or desktop shortcut.

  6. Start Servers

    Click the "Start Servers" button to begin using MAMP.

Configuring Your Local Environment

Basic XAMPP Configuration

Starting and Stopping Services

The XAMPP Control Panel allows you to start and stop the Apache and MySQL services:

  • Click the "Start" button next to Apache to start the web server
  • Click the "Start" button next to MySQL to start the database server
  • Both services should show a green status when running correctly

You should start both services whenever you're developing PHP applications.

Testing Your Installation

  1. Start Apache and MySQL services from the XAMPP Control Panel
  2. Open your web browser and navigate to http://localhost or http://127.0.0.1
  3. You should see the XAMPP welcome page
  4. Click on "phpMyAdmin" in the navigation to verify database connectivity

Document Root Directory

The document root is where you'll place your PHP files and WordPress installation:

  • Windows: C:\xampp\htdocs\
  • macOS: /Applications/XAMPP/xamppfiles/htdocs/
  • Linux: /opt/lampp/htdocs/

Any files placed in this directory will be accessible through your browser at http://localhost/filename.

Best Practice: Create a separate folder for each project within the htdocs directory. For example:

  • htdocs/project1/
  • htdocs/wordpress/
  • htdocs/test/

This organization helps keep your projects separate and easier to manage.

PHP Configuration

XAMPP's PHP configuration is stored in the php.ini file. You might need to modify it for specific requirements:

  • Windows: C:\xampp\php\php.ini
  • macOS: /Applications/XAMPP/xamppfiles/etc/php.ini
  • Linux: /opt/lampp/etc/php.ini

Common settings to adjust include:

  • memory_limit: Increase for memory-intensive applications
  • upload_max_filesize: Increase for uploading larger files
  • post_max_size: Should be larger than upload_max_filesize
  • max_execution_time: Increase for complex scripts

After modifying php.ini, restart Apache for changes to take effect.

Basic MAMP Configuration

Starting and Stopping Services

The MAMP interface includes a "Start/Stop Servers" button that controls both Apache and MySQL simultaneously.

Document Root Directory

By default, MAMP uses the following document root:

  • macOS: /Applications/MAMP/htdocs/
  • Windows: C:\MAMP\htdocs\

You can change this location in MAMP preferences:

  1. Click "Preferences" in the MAMP interface
  2. Go to the "Web Server" tab
  3. Click the folder icon to select a different document root

PHP Version Selection

MAMP makes it easy to switch between PHP versions:

  1. Click "Preferences" in the MAMP interface
  2. Go to the "PHP" tab
  3. Select your desired PHP version from the dropdown menu

For WordPress development, PHP 7.4 or later is recommended.

Port Configuration

MAMP may use non-standard ports by default (8888 for Apache, 8889 for MySQL). To change to standard ports:

  1. Click "Preferences" in the MAMP interface
  2. Go to the "Ports" tab
  3. Click "Set to default Apache and MySQL ports" (changes to 80 and 3306)
  4. Click "OK" and restart the servers

Setting Up a Database for WordPress

WordPress requires a MySQL database. Here's how to create one using phpMyAdmin:

Creating a Database with phpMyAdmin

  1. Access phpMyAdmin

    With Apache and MySQL running, access phpMyAdmin:

    • XAMPP: Click "Admin" next to MySQL in the XAMPP Control Panel, or navigate to http://localhost/phpmyadmin
    • MAMP: Click "Open WebStart page" then "phpMyAdmin" or navigate to http://localhost:8888/phpMyAdmin (or http://localhost/phpMyAdmin if using standard ports)
  2. Create a New Database
    1. Click "New" in the left sidebar
    2. Enter a database name (e.g., "wordpress")
    3. Select "utf8mb4_unicode_ci" as the collation (recommended for WordPress)
    4. Click "Create"
  3. Create a Database User (Optional but Recommended)
    1. Click "User accounts" tab
    2. Click "Add user account"
    3. Enter a username (e.g., "wordpress_user")
    4. Choose "Local" for host
    5. Enter a password
    6. Under "Global privileges" check "Check all"
    7. Click "Go" to create the user

Tip: For local development, you can use "root" with no password (XAMPP's default), but creating a specific user better simulates production environments and is good practice.

Access phpMyAdmin New Database Database User Configure WordPress WordPress Installation Create Create

Testing Your PHP Setup

Creating a Test PHP File

Let's create a simple PHP file to confirm everything is working properly:

  1. Navigate to your document root directory:
    • XAMPP: C:\xampp\htdocs\ (Windows) or similar on other platforms
    • MAMP: /Applications/MAMP/htdocs/ (macOS) or similar on Windows
  2. Create a new file named "phpinfo.php"
  3. Add the following code to the file:
<?php
// Shows detailed information about PHP configuration
phpinfo();
?>

Save the file and access it in your browser at http://localhost/phpinfo.php. You should see a page displaying detailed information about your PHP configuration.

Testing Database Connectivity

Let's create another file to test database connectivity:

  1. Create a new file named "db_test.php" in your document root
  2. Add the following code to the file:
<?php
// Database connection settings
$servername = "localhost";
$username = "root";  // Default XAMPP/MAMP username
$password = "";      // Default XAMPP password (empty)
                    // For MAMP, the default password is usually "root"
$dbname = "test";    // Default database name

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

echo "Connected successfully to MySQL!";

// Close connection
$conn->close();
?>

Save the file and access it in your browser at http://localhost/db_test.php. You should see "Connected successfully to MySQL!" if everything is working correctly.

Troubleshooting Database Connection

  • Connection failed error:
    • Verify MySQL is running in the XAMPP/MAMP control panel
    • Check username and password (MAMP default password is usually "root")
    • Ensure the specified database exists (the "test" database is created by default)
  • Access denied error:
    • Check user privileges in phpMyAdmin
    • Verify the correct username and password are being used

Common Issues and Solutions

Apache Won't Start

Symptoms: The Apache service won't start or immediately stops after attempting to start.

Common Causes:

  • Port Conflict: Another application is already using port 80/443

    Solution: Change Apache ports in httpd.conf file (look for "Listen 80") or stop conflicting applications (Skype, IIS, etc.)

  • Incorrect Configuration: Syntax error in Apache configuration files

    Solution: Check Apache error logs in the XAMPP/MAMP logs directory

  • Windows Security: Windows blocking Apache from running

    Solution: Run XAMPP as administrator or add exceptions to firewall

MySQL Won't Start

Symptoms: The MySQL service won't start or immediately stops after attempting to start.

Common Causes:

  • Port Conflict: Another MySQL instance is already running

    Solution: Change MySQL port in my.ini/my.cnf file or stop the other MySQL instance

  • Corrupted Data: MySQL data files are corrupted

    Solution: Backup and then reinstall MySQL or restore from a known good backup

  • Insufficient Permissions: MySQL can't access its data directory

    Solution: Check folder permissions on the MySQL data directory

PHP Files Show as Plain Text

Symptoms: PHP code is displayed in the browser instead of being executed.

Common Causes:

  • PHP Module Not Loaded: Apache isn't configured to process PHP files

    Solution: Verify PHP module is loaded in httpd.conf

  • Incorrect File Extension: File doesn't have .php extension

    Solution: Rename file with .php extension

  • Syntax Error: PHP opening tag is incorrectly written

    Solution: Ensure PHP code starts with <?php, not <? or other variations

Permission Issues

Symptoms: Can't create or modify files, or get "Permission denied" errors.

Common Causes:

  • Insufficient File Permissions: Web server doesn't have write access

    Solution:

    • Windows: Right-click folder > Properties > Security > Edit > Add "Everyone" with appropriate permissions
    • macOS/Linux: chmod 755 for directories and chmod 644 for files
  • SELinux/Security Policies: System security preventing access

    Solution: Temporarily disable security features for development or configure appropriate exceptions

Real-World Application: Setting Up WordPress

Now that we have our local server environment configured, let's implement a practical example by installing WordPress locally.

Installing WordPress Locally

  1. Download WordPress

    Visit WordPress.org and download the latest version of WordPress.

  2. Extract WordPress Files

    Extract the downloaded ZIP file to your document root directory. You may want to create a subdirectory for your WordPress installation (e.g., "wordpress").

  3. Create a Database

    Follow the database creation steps provided earlier to create a database for WordPress.

  4. Configure WordPress
    1. Navigate to your WordPress directory in a browser (e.g., http://localhost/wordpress)
    2. Click "Let's go!" on the welcome screen
    3. Enter your database information:
      • Database Name: The name you created (e.g., "wordpress")
      • Username: "root" (or your custom username)
      • Password: "" (empty for XAMPP) or "root" (for MAMP)
      • Database Host: "localhost"
      • Table Prefix: "wp_" (default) or customize it
    4. Click "Submit" to proceed
  5. Complete Installation
    1. Click "Run the installation"
    2. Fill in the site information:
      • Site Title: Your site's name
      • Username: Admin username (don't use "admin" for security)
      • Password: A strong password
      • Email: Your email address
      • Search Engine Visibility: Check or uncheck as desired
    3. Click "Install WordPress"
  6. Log In

    After installation completes, log in with your new username and password.

Tip: For multiple WordPress installations, consider using different database prefixes (e.g., "project1_" instead of "wp_") to avoid table name conflicts if you ever need to merge databases.

Advanced Topic: Setting Up Virtual Hosts

Virtual hosts allow you to access your local sites using custom domain names (e.g., http://myproject.local) instead of http://localhost/myproject. This better simulates a production environment and is particularly useful when developing WordPress sites.

Setting Up Virtual Hosts in XAMPP

Step 1: Edit httpd-vhosts.conf

  1. Navigate to the Apache configuration directory:
    • Windows: C:\xampp\apache\conf\extra\
    • macOS: /Applications/XAMPP/xamppfiles/etc/extra/
    • Linux: /opt/lampp/etc/extra/
  2. Open "httpd-vhosts.conf" in a text editor
  3. Add your virtual host configuration:
<VirtualHost *:80>
    DocumentRoot "C:/xampp/htdocs"
    ServerName localhost
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "C:/xampp/htdocs/wordpress"
    ServerName mywordpress.local
    ServerAlias www.mywordpress.local
    <Directory "C:/xampp/htdocs/wordpress">
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Require all granted
    </Directory>
    ErrorLog "logs/mywordpress.local-error.log"
    CustomLog "logs/mywordpress.local-access.log" common
</VirtualHost>

Adjust the paths according to your system and project location.

Step 2: Enable Virtual Hosts

  1. Navigate to the Apache main configuration directory:
    • Windows: C:\xampp\apache\conf\
    • macOS: /Applications/XAMPP/xamppfiles/etc/
    • Linux: /opt/lampp/etc/
  2. Open "httpd.conf" in a text editor
  3. Find the line # Include conf/extra/httpd-vhosts.conf
  4. Remove the # symbol to uncomment the line
  5. Save the file

Step 3: Edit Hosts File

  1. Navigate to your hosts file location:
    • Windows: C:\Windows\System32\drivers\etc\
    • macOS/Linux: /etc/
  2. Open the "hosts" file as administrator/with sudo
  3. Add the following line: 127.0.0.1 mywordpress.local www.mywordpress.local
  4. Save the file

Step 4: Restart Apache

Restart the Apache service in the XAMPP Control Panel for changes to take effect.

Step 5: Test Your Virtual Host

Open your browser and navigate to http://mywordpress.local. You should see your WordPress site.

Setting Up Virtual Hosts in MAMP Pro

MAMP Pro provides a user-friendly interface for setting up virtual hosts:

  1. Open MAMP Pro
  2. Click the "Hosts" tab
  3. Click the "+" button to add a new host
  4. Configure the host:
    • Server Name: mywordpress.local
    • Document Root: Select your WordPress directory
  5. Click "Save"
  6. Restart servers

MAMP Pro will automatically update your hosts file. If you're using the free version of MAMP, you'll need to manually edit the configuration files similar to the XAMPP instructions.

What's Next?

Now that you have a working local server environment and understand the basics of setting it up, you're ready to dive deeper into PHP and WordPress development. In the next sessions, we'll explore:

  • PHP syntax and basic constructs
  • Variables, data types, and operators
  • Including files and PHP in HTML
  • WordPress core concepts
  • Theme and plugin development

Homework Assignment

  1. Install XAMPP or MAMP on your computer
  2. Create and test the PHP examples shown in class (phpinfo.php and db_test.php)
  3. Install WordPress locally
  4. Create a simple PHP script that:
    • Connects to your database
    • Creates a new table named "students" with columns for id, name, email, and registration_date
    • Inserts at least three records into the table
    • Retrieves and displays the records in an HTML table
  5. Optional challenge: Set up a virtual host for your WordPress installation

Submit your PHP script files and screenshots showing your working local environment to the course management system.

Additional Resources