ApacheMySQLPHP
To find the Ubuntu Server Guide related to your specific version, please go to: https://help.ubuntu.com/, select your Ubuntu version and then click on Ubuntu Server Guide. For the latest LTS version (14.04.1 LTS) of Ubuntu Server, please go to https://help.ubuntu.com/14.04/serverguide/index.html
-
- Hint: Server Guide
- Checking Apache 2 installation
- Troubleshooting Apache
- Virtual Hosts
- Checking PHP 5 installation
- Troubleshooting PHP 5
- php.ini development vs. production
- PHP in user directories
- Set mysql bind address
- Set mysql root password
- Create a mysql database
- Create a mysql user
- Backup-Settings
- Alternatively
- Troubleshooting Phpmyadmin & mysql-workbench
- Alternative: install phpMyAdmin from source
- Mysql-workbench
- For more information
- Password-Protect a Directory With .htaccess
- Skype incompatibility
This is to help people set up and install a LAMP (Linux-Apache-MySQL-PHP) server in Ubuntu, including Apache 2, PHP 5 and MySQL 4.1 or 5.0.
To install the default LAMP stack in Ubuntu 10.04 and above
First refresh your package index.
. and then install the LAMP stack:
Mind the caret (^) at the end.
Starting over: How to remove the LAMP stack
- Note: This assumes you have no other programs that require any of these packages. You might wish to simulate this removal first, and only remove the packages that don’t cause removal of something desired.
To also remove the debconf data, use the purge option when removing. To get rid of any configurations you may have made to apache, manually remove the /etc/apache2 directory once the packages have been removed.
You may also want to purge these packages:
Installing Apache 2
To only install the apache2 webserver, use any method to install:
It requires a restart for it to work:
Checking Apache 2 installation
With your web browser, go to the URI http://localhost : if you read «It works!», which is the content of the file /var/www/index.html , this proves Apache works.
Troubleshooting Apache
If you get this error:
apache2: Could not determine the server’s fully qualified domain name, using 127.0.0.1 for ServerName
Ubuntu 13.10+
Use a text editor such as «sudo nano» at the command line or «gksudo gedit» on the desktop to create a new file,
to the file, save it, and enable your new configuration file by running the command below.
This can all be done in a single command with the following:
Ubuntu 13.04 and below
In older versions of Apache, the configuration files were located in a different directory. Use a text editor such as «sudo nano» at the command line or «gksudo gedit» on the desktop to create a new file,
to the file and save. This can all be done in a single command with the following:
Virtual Hosts
Apache2 has the concept of sites, which are separate configuration files that Apache2 will read. These are available in /etc/apache2/sites-available. By default, there is one site available called 000-default. This is what you will see when you browse to http://localhost or http://127.0.0.1. You can have many different site configurations available, and activate only those that you need.
As an example, we want the default site to be /home/user/public_html/. To do this, we must create a new site and then enable it in Apache2.
Now, we must deactivate the old site, and activate our new one. Ubuntu provides two small utilities that take care of this: a2ensite (apache2enable site) and a2dissite (apache2disable site).
Finally, we restart Apache2:
If you have not created /home/user/public_html/, you will receive an warning message
To test the new site, create a file in /home/user/public_html/:
Installing PHP 5
To only install PHP5. use any method to install the package
Enable this module by doing
which creates a symbolic link /etc/apache2/mods-enabled/php5 pointing to /etc/apache2/mods-availble/php5 .
Except if you use deprecated PHP code beginning only by «<?» instead of «<?php» (which is highly inadvisable), open, as root, the file /etc/php5/apache2/php.ini , look for the line «short_open_tag = On», change it to «short_open_tag = Off» (not including the quotation marks) and add a line of comment (beginning by a semi-colon) giving the reason, the author and the date of this change. This way, if you later want some XML or XHTML file to be served as PHP, the «<?xml» tag will be ignored by PHP instead of being seen as a PHP code mistake.
Relaunch Apache 2 again:
Checking PHP 5 installation
In /var/www , create a text file called «test.php», grant the world (or, at least, Ubuntu user «apache») permission to read it, write in it the only line: «<?php phpinfo(); ?>» (without the quotation marks) then, with your web browser, go to the URI «http://localhost/test.php»: if you can see a description of PHP5 configuration, it proves PHP 5 works with Apache.
Troubleshooting PHP 5
Does your browser ask if you want to download the php file instead of displaying it? If Apache is not actually parsing the php after you restarted it, install libapache2-mod-php5. It is installed when you install the php5 package, but may have been removed inadvertently by packages which need to run a different version of php.
If sudo a2enmod php5 returns «$ This module does not exist!», you should purge (not just remove) the libapache2-mod-php5 package and reinstall it.
Be sure to clear your browser’s cache before testing your site again. To do this in Firefox 4: Edit → Preferences … Privacy → History: clear your recent history → Details : choose «Everything» in «Time range to clean» and check only «cache», then click on «Clear now».
Remember that, for Apache to be called, the URI in your web browser must begin with «http://». If it begins with «file://», then the file is read directly by the browser, without Apache, so you get (X)HTML and CSS, but no PHP. If you didn’t configure any host alias or virtual host, then a local URI begins with «http://localhost», «http://127.0.0.1″ or http://» followed by your IP number.
If the problem persists, check your PHP file authorisations (it should be readable at least by Ubuntu user «apache»), and check if the PHP code is correct. For instance, copy your PHP file, replace your whole PHP file content by «<?php phpinfo(); ?>» (without the quotation marks): if you get the PHP test page in your web browser, then the problem is in your PHP code, not in Apache or PHP configuration nor in file permissions. If this doesn’t work, then it is a problem of file authorisation, Apache or PHP configuration, cache not emptied, or Apache not running or not restarted. Use the display of that test file in your web browser to see the list of files influencing PHP behaviour.
php.ini development vs. production
After standard installation, php configuration file /etc/php5/apache2/php.ini is set so as «production settings» which means, among others, that no error messages are displayed. So if you e.g. make a syntax error in your php source file, apache server would return HTTP 500 error instead of displaying the php syntax error debug message.
If you want to debug your scripts, it might be better to use the «development» settings. Both development and production settings ini’s are located in /usr/share/php5/
so you can compare them and see the exact differences.
To make the «development» settings active, just backup your original php.ini
and create a symlink to your desired settings:
or you may of course also edit the /etc/php5/apache2/php.ini directly on your own, if you wish.
PHP in user directories
According to this blog, newer versions of Ubuntu do not have PHP enabled by default for user directories (your public_html folder). See the blog for instructions on how to change this back.
Installing MYSQL with PHP 5
Use any method to install
After installing PHP
You may need to increase the memory limit that PHP imposes on a script. Edit the /etc/php5/apache2/php.ini file and increase the memory_limit value.
After installing MySQL
Set mysql bind address
Before you can access the database from other computers in your network, you have to change its bind address. Note that this can be a security problem, because your database can be accessed by other computers than your own. Skip this step if the applications which require mysql are running on the same machine.
and change the line:
to your own internal ip address e.g. 192.168.1.20
If your ip address is dynamic you can also comment out the bind-address line and it will default to your current ip.
If you try to connect without changing the bind-address you will recieve a «Can not connect to mysql error 10061».
Set mysql root password
Before accessing the database by console you need to type:
At the mysql console type:
A successful mysql command will show:
Query OK, 0 rows affected (0.00 sec)
Mysql commands can span several lines. Do not forget to end your mysql command with a semicolon.
Note: If you have already set a password for the mysql root, you will need to use:
(Did you forget the mysql-root password? See MysqlPasswordReset.)
Create a mysql database
Create a mysql user
For creating a new user with all privileges (use only for troubleshooting), at mysql prompt type:
For creating a new user with fewer privileges (should work for most web applications) which can only use the database named «database1», at mysql prompt type:
yourusername and yourpassword can be anything you like. database1 is the name of the database the user gets access to. localhost is the location which gets access to your database. You can change it to ‘%’ (or to hostnames or ip addresses) to allow connections from every location (or only from specific locations) to the database. Note, that this can be a security problem and should only be used for testing purposes!
To exit the mysql prompt type:
Since the mysql root password is now set, if you need to use mysql again (as the mysql root), you will need to use:
and then enter the password at the prompt.
Backup-Settings
Please, let’s say something in which directories mysql stores the database information and how to configure a backup
Alternatively
There is more than just one way to set the mysql root password and create a database. For example mysqladmin can be used:
mysqladmin is a command-line tool provided by the default LAMP install.
Phpmyadmin and mysql-workbench
All mysql tasks including setting the root password and creating databases can be done via a graphical interface using phpmyadmin or mysql-workbench.
Use any method to install
Troubleshooting Phpmyadmin & mysql-workbench
If you get blowfish_secret error: Choose and set a phrase for cryptography in the file /etc/phpmyadmin/blowfish_secret.inc.php and copy the line (not the php tags) into the file /etc/phpmyadmin/config.inc.php or you will receive an error.
If you get a 404 error upon visiting http://localhost/phpmyadmin: You will need to configure apache2.conf to work with Phpmyadmin.
Include the following line at the bottom of the file, save and quit.
Alternative: install phpMyAdmin from source
See the phpMyAdmin page for instructions on how to install phpmyadmin from source:
Mysql-workbench
Mysql-workbench runs locally, on the desktop. Use any method to install
For more information
Edit Apache Configuration
You may want your current user to be the PHP pages administrator. To do so, edit the Apache configuration file :
Search both the strings starting by «APACHE_RUN_USER» and «APACHE_RUN_GROUP», and change the names to the current username and groupname you are using. Then you’ll need to restart Apache. (look at the next chapter concerning apache commands)
Configuration options relating specifically to user websites (accessed through localhost/
username) are in /etc/apache2/mods-available/userdir.conf and managed with the a2enmod and a2dismod commands.
Installing suPHP
suPHP is a tool for executing PHP scripts with the permissions of their owners. It consists of an Apache module (mod_suphp) and a setuid root binary (suphp) that is called by the Apache module to change the uid of the process executing the PHP interpreter.
Note: suPHP enforces, security and helps avoid file permission problems under development environments with several users editing the site files, but it also demands more memory and CPU usage, which can degrade your server performance under certain circumstances.
To only install suPHP. use any method to install the package
Enable this module by doing
then use a text editor such as «sudo nano» at the command line or «gksudo gedit» on the desktop to edit this file
make a new empty line at the top of the content, then add
make a new empty line at the bottom of the content, then add
For security reasons we need to specify to suPHP what are the document paths allowed to execute scripts, use a text editor such as «sudo nano» at the command line or «gksudo gedit» on the desktop to edit this file
find the value «docroot» and specify the document path of your site files, for example:
that value restrict script execution only to files inside «/var/www/»
that value restrict script execution only to files inside a custom home folder for each configured user inside «/var/www/:$
/public_html» for this tutorial we are going to use this value
which is the same Apache directory directive set before in this document
to restart Apache, type in your terminal
Now lets create a test script to see if suPHP is working correctly, in your terminal type
that command creates a quick php test file to display the current user executing the script
open your browser and navigate to «localhost/whomi.php», most likely the browser will show you a «500» server error, this is because suPHP does not allow too permissive file and folder permissions and also does not allow mixed file and folder ownership, to correct this type in your terminal
those commands enforce a secure and correct file and folder permission and also set a correct user and group ownership for all of them
Now open your browser and navigate to «localhost/whomi.php», if everything went fine you should see the name of the file owner executing the script and not «www-data» unless you specified so
Run, Stop, Test, And Restart Apache
Use the following command to run Apache :
To test configuration changes, use :
Finally, to restart it, run :
Alternatively, you can use a graphical interface by installing Rapache or the simpler localhost-indicator.
Using Apache
You can access apache by typing 127.0.0.1 or http://localhost (by default it will be listening on port 80) in your browser address bar. By default the directory for apache server pages is /var/www . It needs root access in order to put files in. A way to do it is just starting the file browser as root in a terminal:
if you want to make /var/www your own. (Use only for non-production web servers — this is not the most secure way to do things.)
Status
To check the status of your PHP installation:
and insert the following line
Securing Apache
If you just want to run your Apache install as a development server and want to prevent it from listening for incoming connection attempts, this is easy to do.
Change ports.conf so that it contains:
Save this file, and restart Apache (see above). Now Apache will serve only to your home domain, http://127.0.0.1 or http://localhost.
Password-Protect a Directory
There are 2 ways to password-protect a specific directory. The recommended way involves editing /etc/apache2/apache2.conf . (To do this, you need root access). The other way involves editing a .htaccess file in the directory to be protected. (To do this, you need access to that directory).
Password-Protect a Directory With .htaccess
Warning: On at least some versions of Ubuntu, .htaccess files will not work by default. See EnablingUseOfApacheHtaccessFiles for help on enabling them.
thumbnails
If you direct your web browser to a directory (rather than a specific file), and there is no «index.html» file in that directory, Apache will generate an index file on-the-fly listing all the files and folders in that directory. Each folder has a little icon of a folder next to it.
To put a thumbnail of that specific image (rather than the generic «image icon») next to each image file (.jpg, .png, etc.):
. todo: add instructions on how to do thumbnails here, perhaps using Apache::AutoIndex 0.08 or Apache::Album 0.95 .
Known problems
Skype incompatibility
Skype uses port 80 for incoming calls, and thus, may block Apache. The solution is to change the port in one of the applications. Usually, port 81 is free and works fine. To change the port number in Skype go to menu Tools > Options, then click on the Advanced tab, then in the box of the port for incoming calls write your preference.
LAMP (apache mysql php)
В этой статье описана установка и настройка LAMP (Linux-Apache-MySQL-PHP) сервера на базе Ubuntu включающего Apache 2, PHP 5, и MySQL 5.0.
Установка стандартного набора LAMP
Начиная с Ubuntu 7.04 (Feisty Fawn) поумолчанию установлена полезная утилита Tasksel(англ.). Она поможет вам установить LAMP. Просто выполним команду:
При установке будет запрошен пароль для создания администратора БД MySQL.
Удаление LAMP
Для удаления LAMP вам придется удалить его компоненты отдельно:
Установка Apache 2
Если требуется установить только веб-сервер Apache 2 используйте любой метод для того, чтобы установить пакет apache2 . Для того, чтобы Apache заработал его следует перезапустить:
Возможные ошибки
Если при запуске появляется следующая ошибка
apache2: Could not determine the server's fully qualified domain name, using 127.0.0.1 for ServerName
запустите свой любимй текстовый редактор (например sudo nano или gksu gedit ) и создайте файл /etc/apache2/conf.d/fqdn , со следующим содержанием:Это так же можно сделать выполнив комманду:
Виртуальные хосты
Apache2 позволяет создавать различные конфигурационные файлы для сайтов. Они находятся в папке /etc/apache2/sites-available. По-умолчанию создается только один сайт default, на который можно зайти введя в браузере http://localhost или http://127.0.0.1.
Директория для файлов сайта находится в /var/www. Необходимы права root для доступа к этой папке. Но вы можете изменить права на нее командой
Вы также можете создать собственные сайты.
Для примера мы создадим новый сайт в папке /home/user/public_html/ :
Отредактируем новый конфиг-файл в текстовом редакторе выполнив в консоли sudo nano или gksudo gedit , например:
Теперь вы можете деактивировать ваш старый сайт и включить новый. Ubuntu содержит две маленькие утилиты для помощи в этом: a2ensite (apache2enable site) и a2dissite (apache2disable site).
Осталось только перезапустить Apache2:
Если вы не создали папку /home/user/public_html/, то получите сообщение с предупреждением об этом.
Внесем имя сайта в список хостов сервера:
Дописать в строчку 127.0.0.1 localhost через пробел mysite www.mysite Перезапустить Apache2
Для проверки вашего нового сайта создайте файл в папке /home/user/public_html:
И откройте в браузере адрес http://localhost/
Установка PHP 5
Чтобы установить модуль PHP для Apache используйте любой метод для того, чтобы установить пакет libapache2-mod-php5 . Включить модуль PHP 5 в Apache можно выполнив:
Это создаст символическую ссылку /etc/apache2/mods-enabled/php5 указывающую на /etc/apache2/mods-availble/php5 . Если не вы используете устаревшие в PHP короткие теги <? (что крайне нерекомендуемо) вместо <?php откройте от имени суперпользователя файл /etc/php5/apache2/php.ini , найдите в нем строчку
и замените ее на
Это заставит игнорировать открывающие теги <?xml в файлах, обрабатываемых PHP .
Для того, чтобы изменения вступили в силу перезапустите Apache
Проверка PHP
В папке /var/www создайте файл test.php, дайте права на чтение из него всем (или хотя бы пользователю apache ) и запишите в него следующую строку:
Теперь попробуйте в своем браузере перейти на страницу http://localhost/test.php. Если вы видите описание установленного PHP , значит вы все настроили правильно.
Возможные ошибки
Если при выполнении команды sudo a2enmod php5 вы получаете в ответ
попробуйте полностью удалить пакет libapache2-mod-php5
и установить его заново.
Не забывайте очищать кеш браузера перед тем как снова тестировать свой сайт.
Помните, что Apache будет обрабатывать файл только если URI начинается с http:// . Если адрес начинается с file:// , то файл будет отображатся напрямую браузером, по этому вы увидите только CSS и (X)HTML , но не PHP . Если вы не конфигурировали виртуальные хосты, то локальный адрес будет иметь вид http://127.0.0.1 , http://localhost или http://ваш_IP.
Установка MySQL и его модулей для PHP 5
Чтобы установить MySQL используйте любой метод для того, чтобы установить пакеты mysql-server libapache2-mod-auth-mysql php5-mysql .
PhpMyAdmin
Все задачи которые требуется выполнить при момощи MySQL можно делать используя графический интерфейс программ phpmyadmin . Устанавливаем утилиту
При установке она запросит пароли которые были заданы при установке MySQL.
При ошибке 404 внесите в файл /etc/apache2/apache2.conf строчку Include /etc/phpmyadmin/apache.conf
Где лежат настройки Apache/PHP/MySQL?
Путь Описание /etc/mysql/my.cnf Файл настроек MySQL /etc/apache2/apache2.conf Файл настроек Apache 2 /etc/php5/apache2/php.ini Файл настроек PHP5 Как включить отображение ошибок PHP?
В используемом файле настроек php.ini, точное местоположение которого подскажет функция phpinfo() (для устанавливаемого по умолчанию Apache это /etc/php5/apache2/php.ini) за отображение ошибок отвечают следующие опции:
E_DEPRECATED , которое отображает все ошибки.
Ссылки
© 2018 Ubuntu-ru — Русскоязычное сообщество Ubuntu Linux.
© 2012 Canonical Ltd. Ubuntu и Canonical являются зарегистрированными торговыми знаками Canonical Ltd.Быстрая установка Apache, PHP, MySQL и phpMyAdmin на Ubuntu
Откуда взялось слово LAMP, спросите вы. Хоть как бы забавно ни было, это не лампа, а связка программного обеспечения Linux + Apache + MySQL + PHP( Кстати, вместо PHP могут использоваться и другие скриптовые языки. Pyhon или Perl).
Apache – это бесплатный и самый популярный веб сервер под платформы GNU/Linux, Win32, Mac. Для него существует много документации на русском языке.
MySQL – СУБД ( система управления базой данных). В базе данных храниться практически вся информация, которая используется на сайте. Логины, ники, посты, и т.д.
PHP – Скриптовый язык программирования для веб приложений.Приступим
Чтобы поставить всё нужное для организации веб сервера с поддержкой всех нужных инструментов на Linux нужно сделать следущие операции. Для начала нам нужен сам веб сервер Apache. Заходим в терминал и прописываем там команду:
sudo apt-get install apache2 libapache2-mod-auth-mysql
Эта команда скачает и установит с репозитория сам сервер Apache 2, и библиотеку libapache2-mod-auth-mysql.
Затем устанавливает интерпретатор php c дополнительными библиотеками:
sudo apt-get install php5-common php5 libapache2-mod-php5 php5-cli php5-cgi php5-mysql
Для того, чтобы всё заработало нужно перезапустить сервер Apache командой:
sudo /etc/init.d/apache2 reload
Теперь всё работает. Вы можете перейти по адресу localhost и перед вами появиться страница с текстом «Its Works ..» и так далее. Если так оно и есть, значит сервер Apache 2 работает. Проверить же работоспособность php можно создав файл c раcширением php в папке /var/www и открыть его в браузере через адрес
localhost/имя_вашего_файла.php. Чтобы внести изменения в этот каталог вам нужны права администратора, поэтому, вам нужно запустить ваш файловый менеджер от имени администратора. В Ubuntu это делает команда sudo nautilus. Допустим создайте файл test.php, в который вставьте <?php phpinfo(); ?>, если по адресу localhost/test.php выдаст большую синюю страницу с информацией про сервер и настройки php, значит вам удалось установить php.Это выглядит примерно так:
После всех манипуляций с Веб сервером для возможности использовать полную динамичность веб программирования так-же стоит установить СУБД
MySQL. Нужно выполнить в терминале команду:
sudo apt-get install mysql-server mysql-client mysql-admin
Это установит клиент и сервер СУБД MySQL. Установщик спросит пароль для пользователя root в СУБД MySQL. Если вы занимаетесь разработкой приложений, отладкой и тестированием, то можно ставить простой пароль для удобства.
Стоит так-же поставить phpMyAdmin для управления базой данных.
sudo apt-get install phpmyadmin
Выбираем apache2 из предложенного списка.
phpMyAdmin будет доступен по адресу localhost/phpmyadmin. Если при переходе по адресу выдает ошибку, попробуйте выполнить команды:
How to Install Apache, MySQL, and PHP (LAMP) Stack on Ubuntu 20.04 LTS
A LAMP stack is a group of four open-source software components that form the foundation of building and running high-performance dynamic websites and web applications. It’s an acronym for Linux, Apache, MySQL/MariaDB and PHP.
The LAMP stack is simple, stable, and powerful, and its first layer is comprised of the popular Linux Operating System with flexible configuration options and tight security. Apache is the second layer in the pile and offers you compiled module support for major scripting languages such as PHP, Perl, Python, Node.js, etc. This HTTP web server delivers web content through the internet. When it comes to the database layer, you’ve two options when deploying a LAMP stack. You can either use MySQL or MariaDB as an Relational Database Management System (RDMS) for your web applications. The last package in the list is PHP. This is a scripting language that you can easily embed in HTML documents to create static or dynamic websites.
The majority of modern Content Management Systems (CMS) such as WordPress, Joomla, Drupal, and Magento require a LAMP stack to work. Therefore, in this guide, you’ll learn how to configure the right environment for them. The same setup will also work for any custom web application that you may intend to build with the LAMP stack technology.
Prerequisites
To follow along with this guide, you need the following:
1. Install Apache Webserver
SSH to your Ubuntu server as a non-root user, then update the package information index and upgrade your packages.
Next, run the command below to install the Apache Web server.
Visit the URL below on a web browser and replace the 192.0.2.1 with the public IP address of your server or domain name.
You should see the default Apache web page as shown below.

After setting up the web server, you’ll install a database in the next step.
2. Install a Database Server
You can either install MySQL or MariaDB server when deploying a LAMP stack. To install the MySQL server, run the command below.
To set up a MariaDB server, execute the command below.
Irrespective of the database that you’ve chosen, run the command below to secure it.
Enter the below choices and press ENTER in each prompt to proceed.
MySQL Server
MariaDB Server
Once you’ve secure the installation, login to the RDMS as root:
Enter your database server root password and press ENTER to proceed. Then, type the command below to create your first test_database database.
Next, list the databases in the server by running the SHOW DATABASES command.
Your test_database should be in the list below.
Create a test_user and assign full privileges to the database you’ve just created. You’ll require the details of this user when testing database connectivity with PHP. Replace EXAMPLE_PASSWORD with a strong value.
Your database server is now ready and you can move ahead to installing a scripting language.
3. Install PHP
In this step, you’ll install the PHP package. Run the command below.
Since most web applications rely on some PHP extensions, install the most common ones using the command below.
Restart the Apache webserver to load PHP.
To test PHP, create an info.php file in the root directory of your web server.
Then, enter the information below into the file.
Save and close the file by pressing CTRL + X , then Y and ENTER . Then, in a web browser, visit the URL below and replace 192.0.2.1 with your server’s correct public IP address.
You should get a detailed PHP page as shown below.

Next, test PHP connectivity with the database that you created earlier. Open a new file for editing using nano.
Then, enter the information below into the file.
Save and close the file. Then, visit the address below in a web browser and replace 192.0.2.1 with your server’s correct public IP address.
You should get the output below that shows that the script has successfully connected to the database.
Conclusion
Your LAMP stack is now ready on Ubuntu 20.04, and you can now go ahead and build a dynamic website or cloud-based web application.
From here, consider reading about One-Click LAMP stack installation guides and securing your web server with Let’s Encrypt.
For more information about the LAMP stack, see the official documentations: