Setup

Before we start writing PHP code, it's necessary to set up a proper environment for developing, running, and testing our PHP scripts. Here are the basic components we need:

  • Web Server: A software that can serve our PHP pages. Apache and Nginx are two popular options.

  • PHP Processor: This interprets our PHP code and transforms it into HTML that the web server can serve to users' browsers.

  • Database Server (Optional): While not mandatory for all PHP development, a database server such as MySQL or PostgreSQL is essential for dynamic, data-driven websites.

There are two primary ways you can set up your PHP development environment:

Option 1: Local Installation

You can install a web server, PHP, and a database server individually on your own computer.

  • For Windows users, you can download and install each component individually. The links for downloading these components are:

  • For macOS users, PHP and Apache are pre-installed on your machine, and you only need to install MySQL: MySQL for macOS

  • For Linux users, you can install each component using your package manager. For example, on a Ubuntu-based system, you could use the following commands:

    sudo apt-get update
    sudo apt-get install apache2
    sudo apt-get install php
    sudo apt-get install mysql-server

Option 2: Using Docker

If you want to avoid manually managing individual components on your system, you can use Docker. Docker allows you to create containers that bundle all the software you need.

You can find pre-made Docker images for PHP development environments on Docker Hub.

An example of how to pull PHP 8 XAMPP Docker is here:

docker pull tomsik68/xampp:8

Here's a simple docker-compose.yml file for a basic PHP development environment:

version: '3'
services:
  web:
    image: php:apache
    volumes:
      - ./:/var/www/html/
    ports:
      - 8080:80
  db:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: rootpass
      MYSQL_DATABASE: test_db
      MYSQL_USER: test_user
      MYSQL_PASSWORD: test_pass

You can start your environment with the command docker-compose up, and then access your PHP site at http://localhost:8080.

No matter which method you choose for setting up your environment, ensure that everything is set up correctly before you start developing with PHP.

Useful VSCode Extensions:

PHP Intelliphense

Live Server

PHP Server

Last updated