How to Install PHP on Any Server (Linux, macOS, Windows)
Setting up a server can be a daunting task, especially when installing languages like PHP. If you want to get a WordPress test server up and running, it’s a necessary skill to learn. Got no idea where to start to get PHP on your server? Depending on your unique setup, there are many ways to do it. Where do you download PHP, which version, what do you need to make it work, and how do you install PHP on various OSes? We’ll answer them all in this one-stop PHP installation guide. Let’s begin!
Check out our video guide to installing PHP
What is PHP?
PHP is an open source scripting language primarily used for web development and server-side (backend) scripting. In simple terms:
- PHP can be installed on a server to run scripts (e.g. pieces of code to add forms to your site).
- It is run server-side rather than client-side, so it works in the backend rather than in the browser.
- It integrates well with HTML, making it highly suitable for web development.
It’s also one of the easiest web scripting languages to learn, making it a popular choice for beginners. But it’s also quite powerful and suitable for advanced website functions.
Many websites and tools use PHP and its many extensions (.NET, Apache, and MySQL may sound familiar). WordPress is built primarily on PHP, and most of its plugins and themes also run on it.
Does Your Server Need PHP?
So you know what PHP is, but why should you install it on your server?
The most notable reason is that it’s a requirement to get WordPress up and running, as it’s built almost exclusively on PHP. PHP also powers most WordPress functions, hooks, themes, and plugins.
You can see all the other WordPress system requirements here:

So, if you want to run a WordPress test server to play around with or set up a staging site, you’ll need to install PHP.
Besides that, PHP is a great launching point for beginner devs. It’s straightforward to use compared to other web scripting languages, but that doesn’t come at any expense of functionality. You can do all sorts of things with it if you’re skilled enough.
PHP is also quite popular. So, you can find plenty of extensions and resources online.
Besides that, if you want to learn to code WordPress themes and plugins, you’ll need to learn PHP. Setting up a test server is a great way to experiment.
Do note that many web hosting servers (such as Kinsta) come preinstalled with PHP and WordPress. Kinsta even includes the ability to create a WordPress staging site, so that’s easy to get at too.
The only reason you’ll need to do this manually is if you’re setting up a server from scratch, either on your local computer or in an unmanaged hosting environment.
That said, let’s get into the server setup instructions.
guide to set up a local server on multiple OSes. The exact specifics vary depending on your operating system, but you should know how to work with the command line and be ready to install new software.
Whatever operating system you’re installing PHP on, you’ll need a web server to run it. You’ll also likely need to install a database like MySQL, so keep that in mind.
Here are the PHP prerequisites for each OS, starting with Linux:
- An ANSI C compiler.
- Module-specific components like GD graphics libraries or PDF libraries.
- Optional: Autoconf 2.59+ (for PHP versions < 7.0), Autoconf 2.64+ (for PHP versions >7.2), Automake 1.4+, Libtool 1.4+, re2c 0.13.4+, and Bison.
You should also be familiar with navigating Unix-like OSes already.
Now the PHP requirements for Windows:
- Multiple Windows OSes are supported on PHP 5.5+, but 7.2.0+ users cannot use Windows 2008 or Windows Vista.
- Visual C Runtime (CRT).
- Visual Studio 2012, 2015, 2017, or Microsoft Visual C++ Redistributable for Visual Studio 2019, depending on your PHP version.
Lastly, there are no prerequisites for macOS because PHP comes bundled with the system. We’ll explain how to enable it below.
Where to Download PHP
If you need to download the PHP files manually, you should get them from the official site’s PHP downloads page.
Avoid installing it from third-party sites unless you know they’re safe, as downloading files from third-party sites can lead to accidentally installing malware.

If you’re downloading for a Windows machine, look for the “Windows downloads” link in each version of PHP and make sure you’re installing the proper files.
You can also install older versions of PHP, but this is not recommended unless you know what you’re doing, as they expose your server to bugs and major security flaws.
If you’re running a Linux distribution, you usually don’t need to get the files through the website, and you should use the command line. We’ll go over that in detail below.
Which PHP Version Should I Use?
If you’ve clicked that download link above, you’re likely looking at all those files and feeling overwhelmed. Which PHP version is the right one?
Generally speaking, if you’re starting a brand new project where compatibility issues aren’t a problem, you should get the latest stable version of PHP.
It is sometimes possible to download beta versions of PHP, which are even newer, but these are often buggy and only released to help the developers gather feedback. Most of the time, you should stick with the stable releases.
What about older versions? Every PHP version comes with new features, but that means new incompatibilities with older features. If you need to do something specific that
If you’re not sure, then use the latest version of PHP.
Take note that WordPress is only compatible with certain versions of PHP. It technically supports PHP versions starting at 5.6.20+, but these are quite old and thus not recommended. Version 7.4 and 8.0 are currently the best-supported versions for WordPress.
PHP version 8 is also compatible, but currently, this is very new, and not all plugins work properly. If you’re worried about compatibility issues, stick with PHP version 7.4. You can read our PHP benchmarks post to see how various PHP CMSes and frameworks perform on different PHP versions.
Update: PHP 8.1 (official release) is now available to all Kinsta clients. PHP 7.4 is NO LONGER supported at Kinsta. Please note that we support PHP versions 8.0, 8.1, 8.2. This applies to sites hosted at Kinsta only.
How to Install PHP on Linux
Before starting, you should be familiar with the Terminal and how to operate Unix-like OSes in general. Generally, these command line codes should work on any Linux distribution that uses the normal syntax in the Terminal, but we’ve left some notes below for specific OSes.
First, you should make sure your packages are up to date, so run this Linux command in the Terminal.
sudo apt-get update && sudo apt-get upgrade
Now you’re ready to install PHP. The command to do so is effortless and straightforward.
sudo apt-get install php

This will install the latest version of PHP along with several extensions. You can use this code to see which version you have.
php –v
What if you want to install a specific version of PHP, such as PHP 7.4? You’ll need to use a PPA, or Personal Package Archive, by Ondřej Surý. This is a safe way to install older supported versions of PHP. Run these three commands one at a time:
sudo apt install software-properties-common sudo add-apt-repository ppa:ondrej/php sudo apt-get update
Now your system recognizes the archive, and you can install PHP 7.4. Type in the following command:
sudo apt install php7.4
And of course, you can replace this number with whatever PHP version you want.
That covers the basics, but if you need extra help with configuration, the PHP installation documentation for Unix can help.
downloading a LAMP stack. LAMP stands for Linux, Apache, MySQL, and PHP. It’s essentially a bundle of all the software you need to get a server up and running.
While you can manually download each of these tools separately, you could get Taskel, a bundle that will install all these at once. Just run these two commands in succession in the Terminal:
sudo apt install tasksel sudo tasksel install lamp-server

Installing PHP on CentOS 7
This operating system is a little different from other Linux distributions. On CentOS, the apt and apt-get commands are not the ideal ways to install the software. Instead, it uses yum, Yellowdog Updater Modified, a better package manager for RHEL-based operating systems.
Otherwise, the commands you’ll need to use are pretty similar. To update your packages, run this command instead:
sudo yum install epel-release && sudo yum update
As for other commands, you can usually replace apt-get with yum. To install PHP, use this command.
sudo yum install php
PHP commands such as php –v should work the same on CentOS 7, so you don’t need to worry about that.
Installing PHP on Debian
Last for Unix-like operating systems is Debian. This time there are just a few minor concerns, but most of the commands listed above should work fine.
For Debian, you can use either apt-get or aptitude in your Terminal commands. The aptitude command is a little more comprehensive and provides a menu interface. It’s up to personal preference which you use, and either will get the job done.
So instead of using the usual apt-get command, you could run this one instead:
sudo aptitude install php
Debian can be finicky. If you find PHP isn’t parsing or extensions aren’t working, make sure you’ve updated your server’s web configuration file and that it’s loading the extension ini files.
Besides a few small things, instructions for Debian are practically identical to those for other Linux distributions.
How to Install PHP on Windows
If you’re using a Windows system, unlike macOS and Linux, you don’t need to install PHP through the command line (though it is an option if you’d prefer).
An easy way to install PHP from here is to enable IIS and then use WebPI to install PHP. After launching WebPI, you can find it under the Products tab. Click Add on the version you want, then click Install.

You can also download PHP for Windows and manually configure it to work with IIS. Make sure to get a non-thread-safe version if you’re using IIS.
If all this is too complicated, you could instead install WampServer or XAMPP, as these come with everything you need to start working with a web server: Apache, a database, and of course PHP.
These instructions will work with most modern Windows OSes such as Windows 10, 7, and Vista. If you’re using an older version of Windows, you should check out the legacy Windows installation documentation.
Windows may need a little extra configuration to get PHP working properly, so make sure to check the recommended Windows configuration documentation. You just have to make a few small ini tweaks.
How to Install PHP on macOS
PHP comes preinstalled on most macOS systems, so you usually don’t need any manual installation.
All you need to do is uncomment a few lines of code in the Apache configuration file httpd.conf, which you can usually find at /private/etc/apache2/httpd.conf . Uncomment these two lines by removing the hashtag symbol:
# LoadModule php5_module libexec/httpd/libphp5.so # AddModule mod_php5.c
You may need to do extra configuration if you don’t like some file settings’ default values. Otherwise, find the DocumentRoot, then create and load a PHP file with this code:
You can always check the PHP version with the php –v command to make sure PHP was installed correctly.
If you do need to download PHP manually, then you should install Homebrew and use this simple command:
brew install php
All About PHP Extensions
Once you’ve got PHP up and running, it’s a good idea to think about extensions. These compiled libraries add all sorts of extra, helpful functionality. Think of them as plugins that add on to what PHP already offers. Some of these are required to run PHP frameworks, such as Laravel and Symfony.
While it’s completely possible to code everything yourself without ever touching an extension, there’s no reason to do it all on your own when widely-used shortcuts exist to make your life easier.
PHP already comes with dozens of built-in extensions, some of which you must enable manually, and others you can start using right away. You can also install PHP extensions through sites like PECL, which hosts hundreds of third-party packages.
The PHP manual offers extension documentation for many of these as well, so you can get the hang of using them.
Not sure where to start? Here are just a handful of a few popular PHP extensions:
- Apache: Apache is a widely used web server software recommended by WordPress due to its great compatibility with it and PHP. Apache comes bundled with PHP, so you don’t need to install it manually.
- .NET: .NET is a popular software framework that you can use to build web applications and more. It works with multiple languages, including PHP. You may also be interested in PeachPie, which allows you to run PHP code in .NET.
- MySQLi: A better version of the old MySQL extension, MySQLi enables you to work with MySQL database software. This one is a must-have to help you set up your database.
Whenever you install an extension, you need to uncomment it. Just open up php.ini and remove the semicolon (;) in front of extension=extensionname .
You should also check out these PHP frameworks if you’d like to standardize your code and build with premade libraries. They’re a great way to get started with developing web applications with PHP.
Summary
Whatever operating system you’re using, installing PHP isn’t such a hard process. If you want to make a WordPress test server, you’ll need it. Aspiring PHP programmers will find setting up a web server and installing PHP on it a great exercise.
Make sure you download PHP either through the command line or from its official site. You can either get the latest stable version of PHP or any other version compatible with WordPress.
And if you’d like to get started with developing WordPress sites right away, you can try DevKinsta! It comes with PHP preinstalled. It also lets you hot-swap between different PHP versions so that you can test your site in different server environments.
Get all your applications, databases, and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:
- Easy setup and management in the MyKinsta dashboard
- 24/7 expert support
- The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
- An enterprise-level Cloudflare integration for speed and security
- Global audience reach with up to 35 data centers and 260 PoPs worldwide
Get started with a free trial of our Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.
Salman Ravoof
- Website
Установка PHP в Ubuntu
PHP — это очень популярный скриптовый язык программирования с открытым исходным кодом, который часто используется для разработки веб-сайтов и веб-приложений. PHP означает рекурсивный акроним от PHP Hypertext Processor. Скрипты выполняются на стороне сервера и могут находиться как в отдельных файлах, так и быть встроенными в HTML.
На данный момент официально поддерживается три версии PHP — это 5.6, 7.4 и 8. Предыдущие версии больше не получают обновлений безопасности. В этой статье мы рассмотрим как выполняется установка PHP Ubuntu. Будем устанавливать только поддерживаемые версии. Кроме того, рассмотрим как установить расширения для Apache, а также изменить версию по умолчанию.
Установка PHP в Ubuntu
1. Версия по умолчанию — 7.4
PHP версии 7.4 поставляется в официальных репозиториях Ubuntu, поэтому если вы хотите эту версию, то можете очень просто установить ее с помощью команды apt. Сначала смотрим информацию:
sudo apt show php

Теперь для установки версии из репозиториев наберите:
sudo apt install php
Для того чтобы интерпретатор php работал с Apache необходимо установить ещё этот пакет:
sudo apt install libapache2-mod-php

После этого можно посмотреть версию php в терминале:

2. Устаревшая версия — 5.6
Если вам нужна другая версия PHP, например, 5.6, то вам придется добавить в систему репозиторий PPA. Сначала необходимо установить зависимости:
sudo apt install python-software-properties
Затем для добавления PPA репозитория выполните:
sudo add-apt-repository ppa:ondrej/php
Теперь вы можете установить php ubuntu нужной вам версии. В данном случае 5.6. Для Apache выполните такие команды:
sudo apt install php5.6 libapache2-mod-php5.6

Затем можно смотреть версию:

Обратите внимание, что установленная версия PHP не конфликтует с версией из официальных репозиториев. Обе версии могут существовать в системе и между ними можно переключаться.
3. Новая версия — 8.0
На момент написания статьи, версия PHP 8.0 вышла относительно недавно и в официальных репозиториях LTS релиза Ubuntu её нет. В этой версии было много улучшений и исправлений и если вы хотите её попробовать, то можете установить из того же самого PPA:
sudo add-apt-repository ppa:ondrej/php
Затем, как и в предыдущем пункте необходимо указать версию php, которая вам нужна в команде установки:
sudo apt install php8.0 libapache2-mod-php8.0

После завершения установки интерпретатор появится в системе:

Установка расширений PHP
Не зависимо от того какую версию PHP вы установили, обычно для полноценной работы программ необходимо ещё установить расширения. Вот основные расширения, которые требуются чаще всего:
- php-curl — поддержка библиотеки CURL для отправки сетевых запросов;
- php-memcached — кэширование с помощью Memcache;
- php-mysql — поддержка баз данных MySQL и MariaDB;
- php-pgsql — поддержка PostgreSQL;
- php-gd — обработка графики с помощью библиотеки GD;
- php-imagick — обработка графики с помощью библиотеки ImageMagick;
- php-intl — локализация и интернационализация;
- php-mcrypt — шифрование;
- php-xml — работа с XML файлами и DOM;
- php-zip — работа с ZIP архивами;
- php-mbstring — работа со строками содержащими UTF-8 символы, в том числе и кириллицу.
Для того чтобы установить все эти расширения для версии PHP по умолчанию выполните такую команду:
sudo apt install php-curl php-memcached php-mysql php-pgsql php-gd php-imagick php-intl php-mcrypt php-xml php-zip php-mbstring
Если надо установить расширения PHP для определённой версии, то следует указать эту версию в названии пакета:
sudo apt install php7.4-curl php7.4-memcached php7.4-mysql php7.4-pgsql php7.4-gd php7.4-imagick php7.4-intl php7.4-mcrypt php7.4-xml php7.4-zip php7.4-mbstring

Аналогично можно установить расширения для PHP 5.6 или 8.0.
Выбор версии PHP по умолчанию
Вы можете выбрать какую версию php нужно использовать по умолчанию с помощью утилиты update-alternatives. Сначала смотрим доступные версии:
sudo update-alternatives —config php
После этого следует ввести номер версии, которую вы хотите использовать по умолчанию:

Или можно сразу установить php ubuntu по умолчанию:
sudo update-alternatives —set php /usr/bin/php5.6
Чтобы используемая версия обновилась в Apache нужно подключить правильный модуль и перезагрузить веб-сервер. Например, для того чтобы отключить 7.4 и включить 5.6 выполните:
sudo a2dismod php7.4
sudo a2enmod php5.6
sudo systemctl restart apache2

Установка php 8 Ubuntu выполняется так же. Теперь вы знаете как переключить версию php Ubuntu. Установка и настройка PHP вместе с Nginx отдельная обширная тема и она описана в статье про настройку PHP-FPM.
Выводы
В этой статье мы рассмотрели как выполняется установка PHP 8 ubuntu 20.04 и других версиях системы. Теперь вы знаете как установить не только PHP 8, но и другие поддерживаемые версии. Как видите, это очень просто, вы можете получить нужную версию PHP буквально в несколько кликов. Надеюсь, эта информация была вам полезной.
How to install PHP `mbstring` extension in Ubuntu?
EDIT: Dylan Pierce has confirmed that you can already install some PHP 7.2 extensions in the same way you would for PHP 5. For mbstring in particular, you can execute:
sudo apt-get install php7.2-mbstring
To complement sparkmood’s answer, this now works for PHP 7.2 if you already imported ondrej’s PPA for it.
sudo apt-get install libapache2-mod-php7.2
Don’t forget, either PHP 7 is available through ubuntu’s official repositories or you will need an external PPA.
3 2 2 bronze badges
answered Feb 8, 2016 at 21:35
goncalotomas goncalotomas
2,545 2 2 gold badges 13 13 silver badges 8 8 bronze badges
I’ve figured it out: sudo apt-get install php7.0-mbstring Also works for other php extensions you might need like: sudo apt-get install php7.0-zip sudo apt-get install php7.0-dom I really like how brainless it is to install/activate these modules. I just wish I didn’t have to go on an internet wide goose chase for them.
Feb 25, 2016 at 14:26
Why is nobody fighting this version-in-name stuff? -_-
Aug 16, 2016 at 16:28
I believe that as soon as version 7 covers all of the old 5 libraries, you won’t have to write 7 to get the latest and greatest. Not doing so would probably break build scripts or cause unexpected behavior.
Aug 17, 2016 at 15:13
After installed in Ubuntu 16.04 with LAMP is needed to restart Apache2 service sudo service apache2 restart
Aug 23, 2017 at 15:05
You can just use package php-mbstring without the version number
Jan 11, 2018 at 3:21
sudo apt-get install php-mbstring
I have installed mbstring in php7.0-fpm (7.0.15-0ubuntu0.16.04.4)
answered May 16, 2017 at 11:09
Nanhe Kumar Nanhe Kumar
1,399 12 12 silver badges 9 9 bronze badges
This is correct for Debian Stretch. No need to add the version number. Internally a sub-package with version number is loaded.
Sep 21, 2017 at 9:06
I have added version because i have tested on above version. thanks for you comment
Sep 21, 2017 at 10:20
This is vastly superior to specifying the version on the cli as it seems to adapt to the installed version.
Feb 9, 2018 at 19:01
My experience using the sury package repo on debian 9 (stretch), I had to specify the 7.2 version, because php-mbstring is only supported until php 7.2. By not using the php prefix version, it kept saying it doesn’t exist since by php7.4 (the latest release of php as of today). Make sure to install only php7.2 and not above or it might not work as expected.
Jun 5, 2020 at 13:57
E: Unable to locate package php-mbstring (on buster)
Mar 13, 2021 at 18:03
mbstring is built in libapache2-mod-php5 package, so you can use this command for installing :
sudo apt-get install libapache2-mod-php5
As described in package details :
dba dom ereg exif fileinfo filter ftp gettext hash iconv json libxml mbstring mhash openssl pcre Phar posix Reflection session shmop SimpleXML soap sockets SPL standard sysvmsg sysvsem sysvshm tokenizer wddx xml xmlreader xmlwriter zip zlib.
answered Jul 4, 2014 at 10:31
977 8 8 silver badges 11 11 bronze badges
I have already installed apache2 on my server now if I install «libapache2-mod-php5» on my server will it any problem.
Jul 4, 2014 at 11:03
When I run your line, it break my LAMP — l have to re-install 🙁
Aug 25, 2016 at 4:19
This is poor advice. While some systems have Apache2 installed, many others may not. Executing this command risks breaking otherwise working systems. (Yes, I know I’m years late, but maybe it’ll help someone not try this fix.)
Jan 21, 2020 at 4:14
If you’re using php 5.6
Install php 5.6 mbstring package:
sudo apt-get install php5.6-mbstring
Then add the following line to the bottom of your php.ini file:
extension=php5.6-mbstring.so
sudo service apache2 restart
To find your php.ini file, create a file and insert the following line:
Then open with a browser to see where your php.ini file is located.
answered Jun 14, 2017 at 2:34
ChickenFeet ChickenFeet
233 2 2 silver badges 4 4 bronze badges
In my case it was already installed, but I just needed to do phpenmod mbstring , followed by apachectl graceful .
answered Jan 25, 2017 at 17:34
271 7 7 silver badges 12 12 bronze badges
For Ubuntu 14.04 extension mbstring should be built in.
For Ubuntu 16.04:
sudo apt-get install php7.0-mbstring
answered Jul 26, 2017 at 20:54
simhumileco simhumileco
671 1 1 gold badge 11 11 silver badges 16 16 bronze badges
It requires adding another source for apt for install in 18.04..
Download Page for php7.2-mbstring_7.2.7-0ubuntu0.18.04.2_amd64.deb on AMD64 machines
If you are running Ubuntu, it is strongly suggested to use a package manager like aptitude or synaptic to download and install packages, instead of doing so manually via this website.
You should be able to use any of the listed mirrors by adding a line to your /etc/apt/sources.list like this:
answered Aug 9, 2018 at 17:30
11 1 1 bronze badge
+1 I had to use this solution as well for my Google Cloud Ubuntu 18.04 LTS install before I could use apt-get for the 7.2 mbstring extension, then I was able to use the accepted answer.
Feb 4, 2020 at 0:21
Since the mcrypt itself (the package that php-mcrypt uses to do its crypt stuff) is no longer supported after PHP7.2, As of today, to install it specifically for php7.2, you’ll need to make sure when installing to prefix all php7.2 extensions with php7.2- .
While initially the commands suggested by others to just install it work, when using it with an framework version that requires mcrypt (such as Laravel4.2), it will require you to install mcrypt using pecl. Follow the fix here
answered Jun 5, 2020 at 13:51
111 3 3 bronze badges
You must log in to answer this question.
- 14.04
- php
- extension
-
The Overflow Blog
Linked
Related
Hot Network Questions
Subscribe to RSS
Question feed
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.11.15.1019
Ubuntu and the circle of friends logo are trade marks of Canonical Limited and are used under licence.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu 18.04
A “LAMP” stack is a group of open-source software that is typically installed together to enable a server to host dynamic websites and web apps. This term is actually an acronym which represents the Linux operating system, with the Apache web server. The site data is stored in a MySQL database, and dynamic content is processed by PHP.
In this guide, we’ll install a LAMP stack on an Ubuntu 18.04 server.
Deploy your LAMP applications from GitHub using DigitalOcean App Platform. Let DigitalOcean focus on scaling your app.
Prerequisites
In order to complete this tutorial, you’ll need to have an Ubuntu 18.04 server with a non-root sudo -enabled user account and a basic firewall configured. To set this up, you can follow our initial server setup guide for Ubuntu 18.04.
Step 1 — Installing Apache and Updating the Firewall
The Apache web server is a popular open source web server that can be used along with PHP to host dynamic websites. It’s well-documented and has been in wide use for much of the history of the web.
First, make sure your apt cache is updated with:
If this is your first time using sudo in this session, you’ll be prompted to provide your regular user’s password to validate your permissions.
Once the cache has been updated, you can install Apache with:
After entering this command, apt will tell you which packages it plans to install and how much extra disk space they’ll take up. Press Y and hit ENTER to confirm, and the installation will proceed.
Adjust the Firewall to Allow Web Traffic
Next, assuming that you have followed the initial server setup instructions and enabled the UFW firewall, make sure that your firewall allows HTTP and HTTPS traffic. You can check that UFW has an application profile for Apache like so:
OutputAvailable applications: Apache Apache Full Apache Secure OpenSSH
If you look at the Apache Full profile details, you’ll see that it enables traffic to ports 80 and 443 :
OutputProfile: Apache Full Title: Web Server (HTTP,HTTPS) Description: Apache v2 is the next generation of the omnipresent Apache web server. Ports: 80,443/tcp
To allow incoming HTTP and HTTPS traffic for this server, run:
You can do a spot check right away to verify that everything went as planned by visiting your server’s public IP address in your web browser (see the note under the next heading to find out what your public IP address is if you do not have this information already):
http://your_server_ip
You will see the default Ubuntu 18.04 Apache web page, which is there for informational and testing purposes. It should look something like this:

If you see this page, then your web server is now correctly installed and accessible through your firewall.
How To Find your Server’s Public IP Address
If you do not know what your server’s public IP address is, there are a number of ways you can find it. Usually, this is the address you use to connect to your server through SSH.
There are a few different ways to do this from the command line. First, you could use the iproute2 tools to get your IP address by typing this:
This will give you two or three lines back. They are all correct addresses, but your computer may only be able to use one of them, so feel free to try each one.
An alternative method is to use the curl utility to contact an outside party to tell you how it sees your server. This is done by asking a specific server what your IP address is:
Regardless of the method you use to get your IP address, type it into your web browser’s address bar to view the default Apache page.
Step 2 — Installing MySQL
Now that you have your web server up and running, it is time to install MySQL. MySQL is a database management system. Basically, it will organize and provide access to databases where your site can store information.
Again, use apt to acquire and install this software:
Note: In this case, you do not have to run sudo apt update prior to the command. This is because you recently ran it in the commands above to install Apache. The package index on your computer should already be up-to-date.
This command, too, will show you a list of the packages that will be installed, along with the amount of disk space they’ll take up. Enter Y to continue.
When the installation is complete, run a simple security script that comes pre-installed with MySQL which will remove some dangerous defaults and lock down access to your database system. Start the interactive script by running:
This will ask if you want to configure the VALIDATE PASSWORD PLUGIN .
Note: Enabling this feature is something of a judgment call. If enabled, passwords which don’t match the specified criteria will be rejected by MySQL with an error. This will cause issues if you use a weak password in conjunction with software which automatically configures MySQL user credentials, such as the Ubuntu packages for phpMyAdmin. It is safe to leave validation disabled, but you should always use strong, unique passwords for database credentials.
Answer Y for yes, or anything else to continue without enabling.
VALIDATE PASSWORD PLUGIN can be used to test passwords and improve security. It checks the strength of password and allows the users to set only those passwords which are secure enough. Would you like to setup VALIDATE PASSWORD plugin? Press y|Y for Yes, any other key for No:
If you answer “yes”, you’ll be asked to select a level of password validation. Keep in mind that if you enter 2 for the strongest level, you will receive errors when attempting to set any password which does not contain numbers, upper and lowercase letters, and special characters, or which is based on common dictionary words.
There are three levels of password validation policy: LOW Length >= 8 MEDIUM Length >= 8, numeric, mixed case, and special characters STRONG Length >= 8, numeric, mixed case, special characters and dictionary file Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 1
Regardless of whether you chose to set up the VALIDATE PASSWORD PLUGIN , your server will next ask you to select and confirm a password for the MySQL root user. This is not to be confused with the system root. The database root user is an administrative user with full privileges over the database system. Even though the default authentication method for the MySQL root user dispenses the use of a password, even when one is set, you should define a strong password here as an additional safety measure. We’ll talk about this in a moment.
If you’ve enabled password validation, you’ll be shown the password strength for the root password you just entered and your server will ask if you want to change that password. If you are happy with your current password, enter N for “no” at the prompt:
Using existing password for root. Estimated strength of the password: 100 Change the password for root ? ((Press y|Y for Yes, any other key for No) : n
For the rest of the questions, press Y and hit the ENTER key at each prompt. This will remove some anonymous users and the test database, disable remote root logins, and load these new rules so that MySQL immediately respects the changes you have made.
When you’re finished, test if you’re able to log in to the MySQL console by typing:
This will connect to the MySQL server as the administrative database user root, which is inferred by the use of sudo when running this command. You should see output like this:
OutputWelcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 5 Server version: 5.7.34-0ubuntu0.18.04.1 (Ubuntu) Copyright (c) 2000, 2021, Oracle and/or its affiliates. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql>
To exit the MySQL console, type:
Notice that you didn’t need to provide a password to connect as the root user, even though you have defined one when running the mysql_secure_installation script. That is because the default authentication method for the administrative MySQL user is unix_socket instead of password . Even though this might look like a security concern at first, it makes the database server more secure because the only users allowed to log in as the root MySQL user are the system users with sudo privileges connecting from the console or through an application running with the same privileges. In practical terms, that means you won’t be able to use the administrative database root user to connect from your PHP application. Setting a password for the root MySQL account works as a safeguard, in case the default authentication method is changed from unix_socket to password .
For increased security, it’s best to have dedicated user accounts with less expansive privileges set up for every database, especially if you plan on having multiple databases hosted on your server. Please refer to our guide on How To Create a New User and Grant Permissions on MySQL for detailed instructions on how to create MySQL users and configure database access rights.
Your MySQL server is now installed and secured. Next, we’ll install PHP, the final component in the LAMP stack.
Step 3 — Installing PHP
PHP is the component of your setup that will process code to display dynamic content. It can run scripts, connect to your MySQL databases to get information, and hand the processed content over to your web server so that it can display the results to your visitors.
Once again, leverage the apt system to install PHP. In addition to the php package, you’ll also need libapache2-mod-php to integrate PHP into Apache, and the php-mysql package to allow PHP to connect to MySQL databases. Run the following command to install all three packages and their dependencies:
This should install PHP without any problems. We’ll test this in a moment.
Changing Apache’s Directory Index (Optional)
In some cases, you’ll want to modify the way that Apache serves files when a directory is requested. Currently, if a user requests a directory from the server, Apache will first look for a file called index.html . We want to tell the web server to prefer PHP files over others, to make Apache look for an index.php file first. If you don’t do that, an index.html file placed in the document root of the application will always take precedence over an index.php file.
To make this change, open the dir.conf configuration file in a text editor of your choice. Here, we’ll use nano :
It will look like this:
/etc/apache2/mods-enabled/dir.conf
DirectoryIndex index.html index.cgi index.pl index.php index.xhtml index.htm
Move the PHP index file (highlighted above) to the first position after the DirectoryIndex specification, like this:
/etc/apache2/mods-enabled/dir.conf
DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
When you are finished, save and close the file by pressing CTRL+X . Confirm the save by typing Y and then hit ENTER to verify the file save location.
After this, restart the Apache web server in order for your changes to be recognized. You can do that with the following command:
You can also check on the status of the apache2 service using systemctl :
Sample Output● apache2.service - The Apache HTTP Server Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled) Drop-In: /lib/systemd/system/apache2.service.d └─apache2-systemd.conf Active: active (running) since Thu 2021-07-15 09:22:59 UTC; 1h 3min ago Main PID: 3719 (apache2) Tasks: 55 (limit: 2361) CGroup: /system.slice/apache2.service ├─3719 /usr/sbin/apache2 -k start ├─3721 /usr/sbin/apache2 -k start └─3722 /usr/sbin/apache2 -k start Jul 15 09:22:59 ubuntu1804 systemd[1]: Starting The Apache HTTP Server. Jul 15 09:22:59 ubuntu1804 apachectl[3694]: AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' di Jul 15 09:22:59 ubuntu1804 systemd[1]: Started The Apache HTTP Server.
Press Q to exit this status output.
Installing PHP Extensions (Optional)
To extend the functionality of PHP, you have the option to install some additional modules. To see the available options for PHP modules and libraries, pipe the results of apt search into less , a pager which lets you scroll through the output of other commands:
Use the arrow keys to scroll up and down, and press Q to quit.
The results are all optional components that you can install. It will give you a short description for each:
bandwidthd-pgsql/bionic 2.0.1+cvs20090917-10ubuntu1 amd64 Tracks usage of TCP/IP and builds html files with graphs bluefish/bionic 2.2.10-1 amd64 advanced Gtk+ text editor for web and software development cacti/bionic 1.1.38+ds1-1 all web interface for graphing of monitoring systems ganglia-webfrontend/bionic 3.6.1-3 all cluster monitoring toolkit - web front-end golang-github-unknwon-cae-dev/bionic 0.0~git20160715.0.c6aac99-4 all PHP-like Compression and Archive Extensions in Go haserl/bionic 0.9.35-2 amd64 CGI scripting program for embedded environments kdevelop-php-docs/bionic 5.2.1-1ubuntu2 all transitional package for kdevelop-php kdevelop-php-docs-l10n/bionic 5.2.1-1ubuntu2 all transitional package for kdevelop-php-l10n … :
To learn more about what each module does, you could search the internet for more information about them. Alternatively, look at the long description of the package by typing:
There will be a lot of output, with one field called Description which will have a longer explanation of the functionality that the module provides.
For example, to find out what the php-cli module does, you could type this:
Along with a large amount of other information, you’ll find something that looks like this:
Output… Description: command-line interpreter for the PHP scripting language (default) This package provides the /usr/bin/php command interpreter, useful for testing PHP scripts from a shell or performing general shell scripting tasks. . PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML. . This package is a dependency package, which depends on Ubuntu's default PHP version (currently 7.2). …
If, after researching, you decide you would like to install a package, you can do so by using the apt install command like you have been doing for the other software.
If you decided that php-cli is something that you need, you could type:
If you want to install more than one module, you can do that by listing each one, separated by a space, following the apt install command, like this:
At this point, your LAMP stack is installed and configured. Before you do anything else, we recommend that you set up an Apache virtual host where you can store your server’s configuration details.
Step 4 — Setting Up a Virtual Host (Recommended)
When using the Apache web server, you can use virtual hosts (similar to server blocks in Nginx) to encapsulate configuration details and host more than one domain from a single server. We will set up a domain called your_domain, but you should replace this with your own domain name. To learn more about setting up a domain name with DigitalOcean, see our Introduction to DigitalOcean DNS.
Apache on Ubuntu 18.04 has one server block enabled by default that is configured to serve documents from the /var/www/html directory. While this works well for a single site, it can become unwieldy if you are hosting multiple sites. Instead of modifying /var/www/html , let’s create a directory structure within /var/www for your_domain site, leaving /var/www/html in place as the default directory to be served if a client request doesn’t match any other sites.
Create the directory for your_domain as follows:
Next, assign ownership of the directory with the $USER environment variable, which references the current logged user:
The permissions of your web root directory should be correct if you haven’t modified its umask value, but you can make sure by typing:
Next, create a sample index.html page using nano or your favorite editor:
Inside, add the following sample HTML:
/var/www/your_domain/index.html
Welcome to Your_domain! Success! The your_domain server block is working!
Save and close the file when you are finished.
In order for Apache to serve this content, it’s necessary to create a virtual host file with the correct directives. Instead of modifying the default configuration file located at /etc/apache2/sites-available/000-default.conf directly, let’s make a new one at /etc/apache2/sites-available/ your_domain .conf :
Paste in the following configuration block, which is similar to the default, but updated for our new directory and domain name:
/etc/apache2/sites-available/your_domain.conf
ServerAdmin webmaster@localhost ServerName your_domain ServerAlias www.your_domain DocumentRoot /var/www/your_domain ErrorLog $/error.log CustomLog $/access.log combined
Notice that we’ve updated the DocumentRoot to our new directory and ServerAdmin to an email that the your_domain site administrator can access. We’ve also added two directives: ServerName , which establishes the base domain that should match for this virtual host definition, and ServerAlias , which defines further names that should match as if they were the base name.
Save and close the file when you are finished.
Let’s enable the file with the a2ensite tool:
Disable the default site defined in 000-default.conf :
Next, let’s test for configuration errors:
You should see the following output:
OutputSyntax OK
Restart Apache to implement your changes:
Apache should now be serving your domain name. You can test this by navigating to http:// your_domain , where you should see something like this:

With that, your virtual host is fully set up. Before making any more changes or deploying an application, though, it would be helpful to proactively test out your PHP configuration in case there are any issues that should be addressed.
Step 5 — Testing PHP Processing on your Web Server
In order to test that your system is properly configured for PHP, create a PHP script called info.php . In order for Apache to find this file and serve it correctly, it must be saved to your web root directory.
Create the file at the web root you created in the previous step by running:
This will open a blank file. Add the following text, which is valid PHP code, inside the file:
/var/www/your_domain/info.php
When you are finished, save and close the file.
Now you can test whether your web server is able to correctly display content generated by this PHP script. To try this out, visit this page in your web browser. You’ll need your server’s public IP address or domain name again.
The address you will want to visit is:
http://your_domain/info.php
The page that you come to should look something like this:

This page provides some basic information about your server from the perspective of PHP. It is useful for debugging and to ensure that your settings are being applied correctly.
If you can see this page in your browser, then your PHP is working as expected.
You probably want to remove this file after this test because it could actually give information about your server to unauthorized users. To do this, run the following command:
You can always recreate this page if you need to access the information again later.
Conclusion
Now that you have a LAMP stack installed, you have many choices for what to do next. You’ve installed a platform that will allow you to install most kinds of websites and web software on your server.
As an immediate next step, you should ensure that connections to your web server are secured, by serving them via HTTPS. Follow our guide on how to secure Apache with Let’s Encrypt to secure your site with a free TLS/SSL certificate.
Some other popular options are:
- Install WordPress the most popular content management system on the internet.
- Set Up PHPMyAdmin to help manage your MySQL databases from a web browser.
- Learn how to use SFTP to transfer files to and from your server.
Spin up a Linux virtual machine with Apache, MySQL, and PHP pre-configured and attached in one simple click with DigitalOcean. Let us spin up a LAMP stack server for you in seconds, so you can focus on building a great application.
