Installation #

PHP is a server-side language — which means you need a PHP interpreter installed on your machine before you can run a single line of code. Unlike JavaScript, which ships with the browser, PHP has to be installed explicitly and configured to talk to a web server. That process sounds intimidating, but it actually offers several paths, each suited to a different situation: use an all-in-one bundle like XAMPP when you want to be up and running immediately, or use your operating system’s package manager for a cleaner setup that’s easier to maintain over the long run. This article walks you through every option in full — from Windows and macOS to Linux — along with how to verify that your installation is working correctly.

How PHP Works on a Local Machine #

Before installing, it’s important to understand how PHP works so you can pick the right setup.

PHP is essentially an interpreter — a program that reads your .php files, executes them, and produces output. There are two main modes of use:

flowchart TD
    A[.php file] --> B{Execution Mode}
    B -- "Web Request" --> C[Web Server\nApache / Nginx]
    B -- "Terminal" --> D[PHP CLI\nphp script.php]
    C --> E[PHP Module / PHP-FPM]
    E --> F[PHP Interpreter]
    D --> F
    F --> G[Output HTML / JSON / Text]
    G -- "Web" --> H[Browser]
    G -- "CLI" --> I[Terminal]

Web mode — PHP works alongside a web server (Apache or Nginx). When the browser requests a .php page, the web server forwards the request to the PHP interpreter, which returns the result as HTML. This is the mode used in production.

CLI mode — PHP can be run directly from the terminal, just like Python or Node.js. Useful for running scripts, cron jobs, or simply trying out syntax while learning.

For local development, you need both. Bundles like XAMPP provide Apache + PHP + MySQL all at once. A package-manager installation gives you much more control over each individual component.


Choosing the Right Installation Method #

Not every setup fits every situation. The table below helps you choose:

MethodOSBest ForProsCons
XAMPPWindows, macOS, LinuxBeginners, quick prototypingSingle installer, works out of the boxHard to customize, heavyweight
WAMPWindowsBeginners on WindowsEasy GUIWindows only
MAMPmacOSBeginners on MacGraphical interfaceLimited free version
HomebrewmacOSmacOS developersLightweight, easy to updateRequires CLI
APT / DNFLinuxLinux developersNative, fast, lightweightRequires manual configuration
PHP Built-in ServerAllQuick local testingNo extra installationNot for production
flowchart TD
    A{Operating System?} -- Windows --> B{Experience Level?}
    A -- macOS --> C{Prefer GUI?}
    A -- Linux --> D[Use APT / DNF]
    B -- Beginner --> E[XAMPP]
    B -- Intermediate/Advanced --> F[Laragon or WSL2 + APT]
    C -- Yes --> G[MAMP]
    C -- No --> H[Homebrew]
If you’re on Windows and want an environment closer to production Linux, consider WSL2 (Windows Subsystem for Linux). You can install PHP via APT inside WSL2 and get a far more consistent developer experience.

Installing on Windows #

Windows doesn’t ship with PHP by default, so you’ll need to install it manually. There are two main options in common use.

Using XAMPP #

XAMPP is a bundle that packages Apache, MariaDB, PHP, and Perl into a single installer. It’s the fastest way to have a fully working PHP environment on Windows.

Step 1 — Download the installer:

Visit apachefriends.org and download the XAMPP version that matches the PHP version you need. Always choose a PHP 8.x version for new projects.

Step 2 — Run the installer:

Run the installer file you downloaded. Windows may show a UAC warning — click “Yes”. When the component selection dialog appears, make sure the following components are checked:

Components you must check:
  ✓ Apache
  ✓ PHP
  ✓ MySQL / MariaDB
  ✓ phpMyAdmin (optional, but very useful)

Components beginners can skip:
  ✗ FileZilla FTP Server
  ✗ Mercury Mail Server
  ✗ Tomcat

Step 3 — Choose the installation directory:

By default XAMPP installs to C:\xampp. Leave this default unless you have a specific reason to change it — many tutorials and docs assume this path.

Step 4 — Launch the XAMPP Control Panel:

Once the installation finishes, open the XAMPP Control Panel and click the Start button next to Apache. If it works, Apache’s status will turn green.

Step 5 — Verify PHP:

Open Command Prompt and run:

C:\xampp\php\php.exe -v

Or, if you’ve already added PHP to your system PATH:

php -v

Expected output:

PHP 8.3.x (cli) (built: ...)
Copyright (c) The PHP Group
Zend Engine v4.3.x

Adding PHP to PATH (optional but recommended):

To run php from any directory in the terminal, add the PHP path to your system environment variables:

  1. Open System PropertiesAdvancedEnvironment Variables
  2. Under System variables, find the Path variable and click Edit
  3. Click New and add C:\xampp\php
  4. Click OK on all dialogs
  5. Open a new terminal and test with php -v

Using WAMP #

WAMP (Windows, Apache, MySQL, PHP) is a lighter alternative to XAMPP with a handy system tray icon.

Step 1 — Download WAMP:

Visit wampserver.com and download the 64-bit version (unless your system is genuinely 32-bit).

WAMP requires certain Visual C++ Redistributables. If the installation fails or WAMP won’t start, download and install the 2019 and 2022 Visual C++ Redistributable packages from Microsoft’s official site first.

Step 2 — Install and run:

Run the installer, follow the wizard, and WAMP will add an icon to the Windows system tray. Right-click the icon and select Start All Services.

Step 3 — Verify:

Open your browser and go to http://localhost. If the WAMP welcome page appears, the installation succeeded.


Installing on macOS #

Modern macOS no longer ships with PHP by default since macOS Monterey. There are two ways to install it: via Homebrew (recommended for developers) or via MAMP (for those who prefer a GUI).

Using Homebrew #

Homebrew is the de facto package manager for macOS. If you don’t have it yet, it’s a must-have tool on any macOS developer machine.

Step 1 — Install Homebrew (if you don’t have it):

Open Terminal and run the following command:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

This process requires an internet connection and will ask for your administrator password. When it finishes, follow the instructions in the output to add Homebrew to your PATH (especially important on Macs with Apple Silicon / M1/M2/M3 chips).

Step 2 — Install PHP:

brew install php

Homebrew installs the latest stable PHP version along with all its dependencies. If you need a specific PHP version (for example, for a legacy project):

# Install a specific version
brew install [email protected]

# Activate the version you want
brew link --overwrite --force [email protected]

Step 3 — Verify the installation:

php -v

Step 4 — Check installed extensions:

php -m

This command lists all active PHP extensions. For modern web development, make sure the following extensions are available:

Important extensions to have:
  ✓ curl
  ✓ mbstring
  ✓ pdo
  ✓ pdo_mysql
  ✓ json
  ✓ openssl
  ✓ xml

Running the PHP Built-in Development Server:

Once PHP is installed, you can run a simple development server right away without needing Apache:

# Enter your project directory
cd /path/to/project

# Run the server on port 8000
php -S localhost:8000

# Or with a custom router file
php -S localhost:8000 index.php

Open your browser and go to http://localhost:8000. The PHP built-in server is great for rapid development, but must never be used in production.

Using MAMP #

MAMP (macOS, Apache, MySQL, PHP) provides a graphical interface that makes managing a local server easy.

Step 1 — Download MAMP:

Visit mamp.info and download MAMP (the free version is more than enough for development).

Step 2 — Install and configure:

Open the downloaded .pkg file and follow the installation wizard. MAMP installs to /Applications/MAMP.

Step 3 — Choose the PHP version:

Open MAMP, go to PreferencesPHP, and select the PHP version you want to use.

Step 4 — Start the server:

Click the Start button in MAMP. If it works, the Apache and MySQL icons turn green. Open your browser and go to http://localhost:8888 (MAMP’s default port).

The free MAMP uses port 8888 for Apache and 8889 for MySQL. MAMP Pro allows the use of ports 80 and 3306 (the standard ports). You can change the ports manually in Preferences if you’re using the free version.

Installing on Linux #

Linux is the most comfortable platform for PHP development because the operating system’s built-in package manager provides PHP directly. Here we cover the two most common distros: Ubuntu/Debian and Fedora/RHEL.

Ubuntu / Debian — Using APT #

Ubuntu is the most widely used distro for web development, and APT makes it very easy.

Step 1 — Update the package list:

sudo apt update

Step 2 — Install PHP and essential extensions:

sudo apt install php php-cli php-fpm php-mysql php-curl php-mbstring php-xml php-zip php-json

What each package does:

PackagePurpose
phpMain PHP package with the Apache module
php-cliPHP for running from the command line
php-fpmPHP FastCGI Process Manager (for Nginx)
php-mysqlConnection driver for MySQL/MariaDB
php-curlExtension for HTTP requests
php-mbstringMulti-byte string support (important for Unicode)
php-xmlXML processing
php-zipCreate and extract ZIP archives

Step 3 — Verify the installation:

php -v

Step 4 — Check PHP-FPM status (if using Nginx):

sudo systemctl status php8.3-fpm

Installing a specific PHP version on Ubuntu:

The default Ubuntu repositories may not provide the latest PHP version. Use the PPA from Ondřej Surý to get the newest PHP versions:

# Add the PPA
sudo add-apt-repository ppa:ondrej/php
sudo apt update

# Install a specific version
sudo apt install php8.3 php8.3-cli php8.3-fpm php8.3-mysql php8.3-curl php8.3-mbstring

# Check the installed version
php8.3 -v

Switching between PHP versions (if you have several):

# List available versions
sudo update-alternatives --list php

# Switch the active version
sudo update-alternatives --set php /usr/bin/php8.3

Fedora / RHEL / CentOS — Using DNF #

Step 1 — Update the system:

sudo dnf update

Step 2 — Install PHP:

sudo dnf install php php-cli php-fpm php-mysqlnd php-curl php-mbstring php-xml php-zip

Step 3 — Enable and start PHP-FPM:

sudo systemctl enable php-fpm
sudo systemctl start php-fpm

Step 4 — Verify:

php -v
systemctl status php-fpm

SELinux configuration for Apache + PHP (Fedora/RHEL):

On Fedora/RHEL systems, SELinux is active by default. You may need to set the right context:

# Allow Apache to execute PHP
sudo setsebool -P httpd_execmem on

# Allow Apache to read files in home directories (optional)
sudo setsebool -P httpd_enable_homedirs on

Configuring php.ini #

Once PHP is installed, php.ini is the main configuration file that controls the interpreter’s behavior. Its location varies depending on the OS and installation method:

# Find the active php.ini location
php --ini

The output will show something like:

Configuration File (php.ini) Path: /etc/php/8.3/cli
Loaded Configuration File:         /etc/php/8.3/cli/php.ini

Important Settings for a Development Environment #

Open php.ini with a text editor and adjust the following values for local development:

; ============================================================
; SETTINGS FOR DEVELOPMENT (not for production!)
; ============================================================

; Show all errors in the browser (very helpful while debugging)
display_errors = On
display_startup_errors = On
error_reporting = E_ALL

; Upload size limits
upload_max_filesize = 64M
post_max_size = 64M

; Memory limit PHP can use per request
memory_limit = 256M

; Script execution time limit (seconds)
max_execution_time = 60

; Default timezone (adjust to your location)
date.timezone = Asia/Jakarta

; Enable commonly needed extensions
extension=curl
extension=mbstring
extension=pdo_mysql
extension=openssl
The display_errors = On and error_reporting = E_ALL settings are only for local development environments. On a production server, always set display_errors = Off and log errors to a file instead of the screen. Showing errors in production can expose sensitive information about your application’s structure.

The Difference Between CLI and Web php.ini #

PHP has separate php.ini files for CLI mode and web mode. This is important to understand because sometimes changes in one file don’t affect the other:

/etc/php/8.3/
  ├── cli/
  │   └── php.ini      ← used when you run php from the terminal
  ├── apache2/
  │   └── php.ini      ← used when PHP runs via Apache
  └── fpm/
      └── php.ini      ← used when PHP runs via PHP-FPM (Nginx)

If you change a setting in cli/php.ini but don’t see the effect when accessing via the browser, you most likely need to change apache2/php.ini or fpm/php.ini as well.


Complete Installation Verification #

Once the installation is done, run a thorough verification to make sure everything is working correctly.

Verification via Terminal #

# 1. Check the PHP version
php -v

# 2. Check all active extensions
php -m

# 3. Check the loaded configuration
php --ini

# 4. Run interactive PHP (REPL)
php -a

Inside the interactive mode (php -a), try running some simple code:

<?php
echo "PHP is running smoothly!\n";
echo "Version: " . PHP_VERSION . "\n";
echo "OS: " . PHP_OS . "\n";
?>

Verification via Browser — phpinfo() #

The most comprehensive way to see all information about your PHP installation is to create a phpinfo.php file:

<?php
// Save this file as phpinfo.php in the root of your web server directory
// NEVER leave this file on a production server!
phpinfo();

Access this file via the browser (e.g. http://localhost/phpinfo.php). The resulting page shows all the information: PHP version, active extensions, configuration values, environment variables, and much more.

Delete phpinfo.php when you’re done with it. This file exposes detailed information about your server configuration — file paths, software versions, security settings — that attackers can exploit. Never leave this file on a production server.

Verifying the Database Connection #

If you installed MySQL/MariaDB alongside PHP, test the connection:

<?php
// Test the MySQL connection using PDO
$host = '127.0.0.1';
$dbname = 'test';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "✓ Database connection successful!\n";
} catch (PDOException $e) {
    echo "✗ Connection failed: " . $e->getMessage() . "\n";
}

PHP Development Directory Structure #

Once PHP is installed, it’s important to understand where to keep your project files:

XAMPP (Windows) #

C:\xampp\
  ├── htdocs\              ← web root directory (store projects here)
  │   ├── index.php
  │   └── my-project\
  │       └── index.php
  ├── php\
  │   └── php.ini          ← PHP configuration
  └── apache\
      └── conf\
          └── httpd.conf   ← Apache configuration

Access your project at http://localhost/my-project/.

Homebrew / APT (macOS & Linux) #

/var/www/html/             ← Apache web root (Ubuntu)
  └── my-project/
      └── index.php

/etc/php/8.3/              ← PHP configuration (Ubuntu)
  ├── cli/php.ini
  └── apache2/php.ini

/usr/bin/php               ← PHP CLI binary

Troubleshooting Common Issues #

Some problems that often come up when installing PHP and how to fix them:

Port 80 Already in Use (Windows) #

Apache can’t start because port 80 is being used by another program (usually Skype or IIS):

# Check which program is using port 80
netstat -ano | findstr :80

# Solution 1: Change Apache's port in httpd.conf
# Find: Listen 80
# Replace: Listen 8080

# Solution 2: Stop the program using port 80

PHP Command Not Found (macOS/Linux) #

# ANTI-PATTERN: panic and immediately reinstall
# CORRECT: check whether PHP exists at a different path

which php            # check php location
echo $PATH           # check PATH contents

# If PHP is in /usr/local/bin but not on your PATH:
echo 'export PATH="/usr/local/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc

Extensions Not Being Detected #

# Check whether the extension is installed
php -m | grep mysql

# If it doesn't show up, install the extension
sudo apt install php8.3-mysql   # Ubuntu
brew install [email protected]            # Homebrew usually includes it

# Then restart the web server
sudo systemctl restart apache2

Permission Errors on Linux #

# ANTI-PATTERN: chmod 777 on every file (very insecure)
# chmod -R 777 /var/www/html/

# CORRECT: set proper permissions
sudo chown -R www-data:www-data /var/www/html/my-project/
sudo chmod -R 755 /var/www/html/my-project/
sudo chmod -R 644 /var/www/html/my-project/*.php

Summary #

  • PHP needs an interpreter — it can’t run without an explicit installation. Choose an installation method based on your OS and needs: XAMPP/WAMP for Windows, Homebrew/MAMP for macOS, APT/DNF for Linux.
  • The PHP built-in server (php -S localhost:8000) is handy for quick testing without Apache, but not for production.
  • php.ini is separate for CLI and web server — a change in one file doesn’t automatically apply to the other.
  • display_errors = On is for development only — always turn it off in production to avoid exposing sensitive information.
  • phpinfo() is the fastest way to verify an installation, but delete the file once you’re done.
  • Manage extensions explicitly — install only the extensions your project needs; unneeded extensions just add overhead.
  • Use the Ondřej Surý PPA on Ubuntu when you need a PHP version newer than what the official repositories provide.
  • Permissions on Linux — use 755 for directories and 644 for PHP files, not 777, which opens everything up.

← Previous: Introduction   Next: Core Syntax →

About | Author | Content Scope | Editorial Policy | Privacy Policy | Disclaimer | Contact