Install PHP 8.1 and Set Up a Local Dev Environment on Ubuntu
Source: DigitalOcean
By Jamon Camisso and Vinayak Baranwal A previous version of this tutorial was written by alenaholligan. PHP is a popular, open-source server side scripting language designed for web development and powers a significant portion of the internet from blogs and e-commerce sites to large-scale applications. With each new release, PHP delivers improved performance, security, and modern development features to help developers build robust and scalable software. PHP 8.1 is a stable, long-term supported release that brings notable enhancements and new language features while maintaining reliability. Installing PHP 8.1 on Ubuntu ensures your local development environment is up-to-date, secure, and compatible with widely used frameworks and platforms like WordPress, Laravel, and custom PHP applications. This tutorial guides you through installing PHP 8.1 on Ubuntu, configuring it with Apache or Nginx, setting up essential PHP extensions, and installing Composer for dependency management. You’ll also learn how to verify your installation and troubleshoot common issues. Deploy your PHP applications from GitHub using DigitalOcean App Platform. Let DigitalOcean focus on scaling your app. PHP 8.1 installation on Ubuntu 22.04: Ubuntu 22.04 LTS includes PHP 8.1 in its default repositories, allowing you to install a stable, long-term supported PHP version using apt without third‑party PPAs. This ensures predictable updates, security patches, and compatibility with modern PHP frameworks. Essential PHP extensions for real-world projects: Most production-grade PHP applications rely on extensions like mysql, curl, xml, mbstring, zip, gd, and bcmath. Installing these early prevents runtime errors later and ensures compatibility with frameworks such as Laravel, Symfony, and WordPress. Choosing Apache or Nginx for PHP development: Apache can execute PHP directly using mod_php, while Nginx requires PHP‑FPM for request handling. Both approaches work well for local development, but PHP‑FPM more closely mirrors modern production environments and scales better under load. Composer as the foundation of modern PHP workflows: Composer manages project dependencies through composer.json and composer.lock, ensuring consistent builds across machines. It is essential for installing frameworks, generating autoloaders, and maintaining reliable dependency versions in collaborative PHP projects. Configuring PHP specifically for development: Development environments benefit from verbose error reporting, higher memory limits, and longer execution times. Adjusting these settings in php.ini helps surface bugs quickly during development, but they must always be reverted for production deployments. Troubleshooting and validation are part of setup: Verifying PHP with php -v, checking loaded extensions, and reviewing Apache, Nginx, or PHP‑FPM logs are critical steps. Most setup issues stem from missing extensions, permissions, or misconfigured web server directives. To complete this tutorial, you need: If you’re setting up a new Ubuntu server, see our guide on Initial Server Setup with Ubuntu. You’ll be completing your installation and setup on the command line, which is a non-graphical way to interact with your computer. That is, instead of clicking on buttons, you’ll be typing in text and receiving feedback from your computer through text as well. The command line, also known as a shell or terminal, can help you modify and automate many of the tasks you do on a computer every day and is an essential tool for software developers. There are many terminal commands to learn that can enable you to do more powerful things. The article An Introduction to the Linux Terminal can get you better oriented with the terminal. Note: If you’re new to Ubuntu, consider reviewing our Ubuntu documentation for additional system administration guidance. On Ubuntu, you can find the Terminal application by clicking on the Ubuntu icon in the upper-left-hand corner of your screen and typing terminal into the search bar. Click on the Terminal application icon to open it. Alternatively, you can hit the CTRL, ALT, and T keys on your keyboard at the same time to open the Terminal application automatically. Note: On Ubuntu 22.04 LTS, PHP 8.1 is available in the default repositories. When you install PHP without specifying a version on Ubuntu 22.04, the system installs PHP 8.1 by default. If you need to manage multiple PHP versions or install a different version, consider using phpenv or phpbrew for version management. Run the following commands to update your list of available packages, then install PHP 8.1: The --no-install-recommends flag will ensure that other packages like the Apache web server are not installed. Check your PHP version information with the following command: You will receive output like this: This setup was tested on Ubuntu 22.04 LTS using PHP 8.1 packages from the official Ubuntu repositories. Install essential PHP extensions for web development: This command will install the following modules: PHP configuration files are stored in /etc/php/8.1/. The main configuration file is php.ini, which may be located in different directories depending on your setup: Verify installed extensions: This lists all loaded PHP modules. If php -v shows a different version than expected, you may have multiple PHP versions installed. Use php8.1 -v to verify PHP 8.1 specifically. You have installed PHP and verified the version you have running. You also installed any required PHP modules and were able to list the modules that you have loaded. Install the Apache PHP module: Enable the module and restart Apache: Understanding mod_php: The mod_php module embeds PHP directly into Apache’s process. When Apache receives a request for a PHP file, it processes it internally using the embedded PHP interpreter. This differs from Nginx, which requires a separate PHP-FPM service. The a2enmod command creates a symbolic link in /etc/apache2/mods-enabled/ to activate the module. Verify that Apache is processing PHP correctly by creating a test file in Apache’s document root (typically /var/www/html): Visit http://localhost/info.php in your browser. You should see PHP’s configuration information page. Remove this file after testing for security: If Apache won’t start after installing mod_php: Check Apache’s error log: Common issues include: If you visit localhost and see “It works!” but PHP files show as plain text: This means Apache isn’t processing PHP. Check: If you get a 403 Forbidden error: Check file permissions: Security Note: The phpinfo() function exposes detailed system information. Never leave files containing phpinfo() on production servers. For local development with custom domains, create a virtual host: Add this configuration: Create the directory, enable the site, and restart Apache: Add the domain to your /etc/hosts file for local access: Before configuring your web server, consider which one fits your needs: When to choose Apache: When to choose Nginx: Both work equally well for local development. The choice often comes down to personal preference or existing infrastructure. Install PHP-FPM (FastCGI Process Manager): Start and enable PHP-FPM: Understanding PHP-FPM and FastCGI: Unlike Apache’s mod_php, Nginx doesn’t process PHP directly. PHP-FPM (FastCGI Process Manager) runs as a separate service that Nginx communicates with using the FastCGI protocol. FastCGI is a binary protocol for interfacing programs with web servers—it’s faster than traditional CGI because it keeps processes alive between requests. When Nginx receives a request for a PHP file, it forwards the request to PHP-FPM via a Unix socket (or TCP connection). PHP-FPM processes the PHP code and returns the result to Nginx, which then sends it to the client. This separation allows PHP-FPM to manage its own process pool, improving performance and resource management. Create a server block configuration: Add this configuration: Configuration explained: Enable the site and test the configuration: If the test passes, restart Nginx: Add the domain to /etc/hosts: Create a test PHP file: Visit http://example.local/info.php. You should see PHP’s configuration page. Remove the test file after verification: If you get “502 Bad Gateway” error: This means Nginx can’t communicate with PHP-FPM. Check: You should see something like listen = /run/php/php8.1-fpm.sock. The path in your Nginx config must match exactly. Note that /var/run is often a symlink to /run, so both paths work. The socket should be owned by www-data or the user Nginx runs as. If permissions are wrong: You might see errors like: This indicates the socket path is incorrect or PHP-FPM isn’t running. If PHP files download instead of executing: This means Nginx isn’t passing PHP files to PHP-FPM. Check: If you get “File not found” errors: Check that snippets/fastcgi-php.conf exists: This file sets SCRIPT_FILENAME which tells PHP-FPM which file to execute. Without it, PHP-FPM doesn’t know what file to process. Configure PHP for development by adjusting error reporting, display settings, and memory limits in php.ini. These settings differ from production configurations. PHP uses separate configuration files for CLI (command-line) and web server usage. Edit the appropriate file: For CLI (when running PHP from terminal): For web server (Apache or Nginx with PHP-FPM): Note: If you’re using both CLI and web server, you need to configure both files separately. Changes to cli/php.ini don’t affect web requests, and changes to apache2/php.ini or fpm/php.ini don’t affect CLI scripts. Find and update these settings in your php.ini file: What each setting does: Production Warning: Never use these development settings in production. Always set display_errors = Off and use appropriate error reporting levels on live servers. After making changes, restart your web server: Check if your changes took effect: Visit the test file in your browser and search for display_errors. It should show On. Remove the test file after verification. If your changes don’t appear: You could start using PHP right now, but you will likely want to use various libraries to build PHP applications quickly. Before you test your PHP environment, first set up a dependency manager for your projects. Libraries are a collection of code that can help you solve common problems without needing to write everything yourself. Since there are many libraries available, using a dependency manager will help you manage multiple libraries as you become more experienced in writing PHP. Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and will manage installing and updating these packages. Although similar, Composer is not a package manager in the same sense as yum or apt. It deals with “packages” or libraries, but it manages them on a per-project basis, installing them in a directory (e.g. vendor) inside your project. By default, it does not install anything globally. Thus, it is a dependency manager. It does, however, support a global project for convenience via the global command. This idea is not new, and Composer is strongly inspired by Node’s npm and Ruby’s bundler. Download the Composer installer: Verify the installer’s integrity by checking its SHA-384 hash. Get the latest hash: Verify the hash matches: If you see Installer corrupt, the download was incomplete or tampered with. Download the installer again and verify the hash. If it still fails, check your internet connection or try downloading from a different network. Install Composer globally: You’ll receive output similar to this: Test your installation: You will receive output like the following: This verifies that Composer was successfully installed on your system and is available system-wide. Note: If you prefer to have separate Composer executables for each project you host on your server, you can install it locally, on a per-project basis. This method is also useful when your system user doesn’t have permission to install software system-wide. To do this, use the command php /tmp/composer-setup.php without any arguments. This command will generate a composer.phar file in your current directory, which you can run using php composer.phar. As a final step, you may optionally initialize your project with composer init. This will create the composer.json file that will manage your project dependencies. Initializing the project will also let you define project details such as Author and License, and use Composer’s autoload functionality. You can define dependencies now or add them later. Create a project directory and initialize Composer: Running this command will start the setup wizard. Details that you enter in the wizard can be updated later, so feel free to leave the defaults and just press ENTER. If you aren’t ready to install any dependencies, you can choose no. Enter in your details at each prompt: Before you confirm the generation, you will see a sample of the composer.json file that the wizard will create. If it all looks good, you can confirm the default of yes. If you need to start over, choose no. The first time you define any dependency, Composer will create a vendor folder. All dependencies install into this vendor folder. Composer also creates a composer.lock file. This file specifies the exact version of each dependency and sub-dependency used in your project. This assures that any machine on which your program is run, will be using the exact same version of each package. Note: The vendor folder should never be committed to your version control system (VCS). The vendor folder only contains packages you have installed from other vendors. Those individual vendors will maintain their own code in their own version control systems. You should only be tracking the code you write. Instead of committing the vendor folder, you only need to commit your composer.json and composer.lock files. You can learn more about ignoring specific files in How To Use Git: A Reference Guide. Now that you have PHP installed and a way to manage your project dependencies using Composer, you’re ready to test your environment. Create and run a basic PHP script to test your installation: Add the following PHP code: Save and close the file (press CTRL+X, then Y, then ENTER). Run the script: If the PHP is processed properly, you will see only the characters within the quotes: PHP has successfully processed the script, meaning that your PHP environment is successfully installed and you’re ready to continue your programming journey. Modern PHP frameworks like Laravel, Symfony, and WordPress require specific PHP extensions and Composer. Install the framework using Composer or the framework’s installer, then configure your web server to point to the project’s public directory. Install Laravel using Composer: This command downloads Laravel and all its dependencies. The process may take a few minutes. Laravel requires these PHP extensions (installed in Step 1): If Laravel says “missing mbstring” even though you installed it: This usually means the extension is installed but not loaded. Check: Make sure the extension is enabled in the CLI php.ini file. Verifying Laravel installation: After installation completes, start Laravel’s development server: Visit http://localhost:8000 in your browser. You should see Laravel’s welcome page. For production-like setups with Apache or Nginx: Configure your web server to point to the public directory (not the project root). Laravel’s public/index.php is the entry point for all requests. Note: Learn more about Laravel in our tutorial on How To Install Laravel on Ubuntu. Download and extract WordPress: WordPress requires a MySQL or MariaDB database. Install MySQL if needed: The mysql_secure_installation script will prompt you to: Create a database and user for WordPress: Replace secure_password with a strong password. WordPress will use these credentials to connect to the database. If WordPress can’t connect to the database: If this fails, check: If missing, install it: Completing WordPress installation: Configure your web server to point to /var/www/wordpress (see Step 2 for Apache or Step 3 for Nginx). Visit the site in your browser. WordPress will prompt you to: Note: For detailed WordPress installation, see How To Install WordPress with LAMP on Ubuntu. Install Symfony using Composer: Symfony requires the same extensions as Laravel. Start the development server: Or use PHP’s built-in server: If Symfony installation fails with extension errors: Check that all required extensions are installed and loaded: If any are missing, install them and restart your web server. Secure your local environment, use version control, configure proper file permissions, and set up environment-specific configurations. These practices prevent security issues and make development smoother. Even in local development, follow security best practices: Disable dangerous PHP functions in production: Functions like exec(), system(), and shell_exec() should be restricted in production php.ini files. Use environment variables: Store sensitive configuration in .env files (never commit these to version control). Laravel and Symfony support this natively. Set proper file permissions: Web server files should be readable by the web server user but not writable: Why these permissions matter: Directories need 755 (read, write, execute for owner; read and execute for others) so the web server can traverse them. Files need 644 (read and write for owner; read-only for others) so the web server can read but not modify them. This prevents malicious scripts from overwriting your files. Always use version control for your PHP projects. Initialize Git in your project directory: Create a .gitignore file to exclude unnecessary files: For better performance in local development: Enable OPcache: OPcache is included with PHP 8.1 and improves performance by caching compiled PHP code. Use Composer’s autoloader optimization: Common PHP installation issues include missing extensions, incorrect file permissions, web server configuration errors, and version conflicts. Most problems can be resolved by checking extension installation, verifying file permissions, and reviewing web server logs. If php -m doesn’t show an extension you just installed: Make sure you’re checking the correct php.ini file (CLI vs web server). If the extension still doesn’t appear: A 500 error means the server encountered an error but can’t show details. Check the error logs: Common causes and fixes: Missing PHP extensions: Check the error log for messages like “Call to undefined function”. Install the missing extension and restart the web server. Syntax errors in PHP files: The error log will show the file and line number. Common issues: Incorrect web server configuration: PHP memory limit exceeded: Increase memory_limit in php.ini if you see “Allowed memory size exhausted” errors If php -v shows a different version than expected, you have multiple PHP versions installed. Check which versions are installed: Use the correct version explicitly: Update your web server to use PHP 8.1: For Apache, disable other PHP modules and enable PHP 8.1: For PHP-FPM, stop other versions and start PHP 8.1: Set PHP 8.1 as the default CLI version: If Composer runs out of memory, you’ll see an error like: Fix it by running Composer with increased memory: Or increase PHP’s memory limit in php.ini: If Composer installation fails with a hash mismatch: The hash verification might fail if: If your PHP application can’t connect to MySQL/MariaDB, you might see errors like: Troubleshooting steps: If it’s not running, start it: If missing, install it: If this fails, check: Note: For MySQL setup, see How To Install MySQL on Ubuntu. If your PHP file displays as plain text in the browser: Check the file extension: It must be .php, not .txt or .html Verify PHP is processing files: Check file permissions: The web server must be able to read the file Verify the file contains PHP code: Make sure it starts with <?php or <? Check web server configuration: If file uploads fail, you might see errors like: Check these php.ini settings: Important: post_max_size must be larger than upload_max_filesize. If you set upload_max_filesize = 100M, set post_max_size = 110M or higher. If uploads still fail: Restart your web server after making php.ini changes. Install PHP 8.1 using Ubuntu’s package manager: sudo apt update && sudo apt install php8.1. PHP 8.1 is available in Ubuntu’s default repositories, so no additional package sources are needed. Essential extensions include php8.1-cli, php8.1-mysql, php8.1-curl, php8.1-xml, php8.1-mbstring, php8.1-zip, php8.1-gd, and php8.1-bcmath. These cover database connectivity, HTTP requests, string handling, and image processing. For Apache, install libapache2-mod-php8.1 and enable it with sudo a2enmod php8.1. For Nginx, install php8.1-fpm and configure Nginx to pass PHP requests to the PHP-FPM socket using FastCGI. Run php -v to check the PHP version. Create a test file with <?php phpinfo(); ?> and access it through your web server to see detailed PHP configuration information. Yes. Laravel requires Composer and the standard PHP extensions mentioned above. WordPress needs a MySQL database in addition to PHP. Both frameworks work with either Apache or Nginx configurations. Download the Composer installer, verify its hash, and install it globally: sudo php /tmp/composer-setup.php --install-dir=/usr/local/bin --filename=composer. Verify with composer --version. Check installed extensions with php -m. Install missing extensions using sudo apt install php8.1-extension_name, then restart your web server. Edit php.ini and set display_errors = On, error_reporting = E_ALL, and log_errors = On. Remember to disable error display in production environments. Apache uses mod_php to process PHP directly (PHP is embedded in Apache’s process), while Nginx requires PHP-FPM (FastCGI Process Manager) to handle PHP requests (PHP runs as a separate service). See the “Choosing Between Apache and Nginx” section above for a detailed comparison table. Both approaches work well; choose based on your performance needs, familiarity, and existing infrastructure. Yes, using tools like phpenv or phpbrew. However, for most development scenarios, a single PHP version is sufficient. Use version managers when you need to test applications against different PHP versions. You now have a fully configured PHP 8.1 development environment on Ubuntu with support for both Apache and Nginx web servers. Your setup includes essential PHP extensions, Composer for dependency management, and proper configuration for local development. Before starting your next project, consider setting up an Integrated Development Environment (IDE) like VS Code with PHP extensions for syntax highlighting, debugging, and IntelliSense support. With your environment ready, you can explore PHP development further: For production deployments, consider using DigitalOcean App Platform to deploy your PHP applications directly from GitHub with automatic scaling and SSL certificates. Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about our products PHP is a popular server scripting language known for creating dynamic and interactive web pages. Browse Series: 9 tutorials Building future-ready infrastructure with Linux, Cloud, and DevOps. Full Stack Developer & System Administrator. Technical Writer @ DigitalOcean | GitHub Contributor | Passionate about Docker, PostgreSQL, and Open Source | Exploring NLP & AI-TensorFlow | Nailed over 50+ deployments across production environments. This textbox defaults to using Markdown to format your answer. You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link! This comment has been deleted Running into a confusing issue. I’m Ubuntu 18.04.6, but still attempted to install PHP 8.1 using the command in this, and it stated that it worked, however if I run php -v, I get: If I run the install again, it says php8.1 is already the newest version: to be able to folllow this guide, you have to add this PPA . run the following command
sudo add-apt-repository ppa:ondrej/php Please complete your information! Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation. Full documentation for every DigitalOcean product. The Wave has everything you need to know about building a business, from raising funding to marketing your product. Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter. New accounts only. By submitting your email you agree to our Privacy Policy Scale up as you grow — whether you're running one virtual machine or ten thousand. Sign up and get $200 in credit for your first 60 days with DigitalOcean.* *This promotional offer applies to new accounts only.