XAMPP Apache + MariaDB + PHP + Perl
Tip: By default the installer uses the Qt backend for its UI. If you want it to use the GTK backend instead, launch:
Установка и настройка XAMPP
В этом уроке мы рассмотрим настройку окружения, необходимого для разработки на PHP с помощью пакета XAMPP – это приложение, позволяющее быстро развернуть для локальной разработки связку из PHP, Apache, MariaDB (аналог MySQL). Эта программа, в отличие от OpenServer, настройка которого описана в этой статье, является кросс-платформенной, и может использоваться на компьютерах под управлением Windows, Linux и MacOS.
Прежде всего, скачайте и установите XAMPP с официального сайта.
После установки запустите XAMPP и перейдите во вкладку “Manage Servers”. Выберите в списке “Apache Web Server” и нажмите кнопку “Start”. Напротив выбранного значения, в колонке “Status” будет написано “Running” – сервер Apache в связке с PHP был успешно запущен на вашем локальном компьютере.
Чтобы проверить его работу, откройте ваш браузер и введите в адресной строке адрес http://localhost/ и нажмите Enter. Перед вами откроется приветственное окно XAMPP.
- PhP разработчик для написание модулей под Личный Кабинет 20000₽ – 80000₽
- Backend разработчик (PHP Symfony), Symphony + Vue, БД postgres, знания docker 80000₽ – 150000₽
- Full stack PHP разработчик До 120000₽
- Backend-разработчик (Symfony) 120000₽ – 150000₽
- PHP-разработчик (Symfony) До 250000₽
Настройка виртуальных хостов
Теперь нужно настроить виртуальный хост для нашего первого проекта – это такая штука, благодаря которой можно в браузере вбить адрес сайта, например, blabla.com, и локальный веб-сервер обработает запрос для этого адреса. С помощью XAMPP можно сделать неограниченное количество таких виртуальных хостов.
Для нашего учебного проекта мы создадим виртуальный хост для домена myproject.loc. В первую очередь, давайте создадим директорию, в которой будет располагаться наш проект.
Я создал её по пути /Users/artyom/projects/myproject.loc
В случае Windows путь будет начинаться с буквы диска, на котором расположен проект, например: D:\projects\myproject.loc
- Тест на знание основ HTML
- Тест на знание основ PHP
- Тест на знание ООП в PHP
Внутри этой директории нужно создать папку www – это будет корневая директория нашего сайта для веб-сервера. Именно в папке www веб-сервер будет искать запрашиваемые нами файлы.
Теперь нужно открыть папку с установленным XAMPP (у меня она расположена по пути /Applications/XAMPP), в ней найти папку etc, внутри нее будет папка extra, а в ней будет файл httpd-vhosts.conf
Откройте его в любом текстовом редакторе. В нём вы увидите примеры нескольких конфигураций виртуальных хостов. В моём случае это хосты dummy-host.example.com и dummy-host2.example.com
Добавим к ним наш хост myproject.loc
ServerAdmin [email protected] DocumentRoot "/Users/artyom/projects/myproject.loc/www" ServerName myproject.loc ErrorLog "logs/myproject.loc-error_log" CustomLog "logs/myproject.loc-access_log" common AllowOverride All Require all granted
Теперь о самой конфигурации:
VirtualHost – корневая секция виртуального хоста. *:80 означает что этот хост будет доступен по любому IP-адресу и слушать 80 порт. Настройки хоста расположены внутри этой секции.
ServerAdmin – здесь можно указать ваш контактный email.
DocumentRoot – здесь указываем путь до папки www, которую мы создали ранее.
ServerName – здесь указываем доменное имя для нашего хоста, это домен, по которому сайт будет открываться в браузере.
ErrorLog – путь для файла с логами ошибок. В него будут записываться ошибки, которые порой случаются даже на самых надежных сайтах.
CustomLog – путь для файла с логами доступа. Сюда просто будут записываться все запросы пользователей.
Directory – настройки конкретной директории. В нашем случае мы настраиваем нашу корневую директорию виртуального хоста. Require all granted означает что разрешены запросы с любых адресов. AllowOverride All – разрешает использовать .htaccess-файл для конфигурирования сайта. Об этом мы поговорим позже в курсе PHP.
Теперь нужно сделать так, чтобы веб-сервер Apache применял эти настройки, описанные в файле httpd-vhosts.conf
Для этого нужно снова открыть папку с установленной программой XAMPP, найти в ней папку etc, а в ней найти файл httpd.conf
Открываем его в любом текстовом редакторе, и ищем строку:
Include etc/extra/httpd-vhosts.conf
Её нужно раскомментировать (убрать символ # в начале строки).
После внесения изменений файл нужно сохранить.
После внесения изменений нужно чтобы веб-сервер Apache перечитал конфигурацию и работал с новыми настройками. Для этого его нужно перезапустить. Открываем панель управления XAMPP, выбираем в списке “Apache Web Server” и нажимаем кнопку “Restart”.
Настройка /etc/hosts
Теперь нужно внести изменения в ещё один файл – /etc/hosts
В этом файле можно явно указать привязку доменного имени к IP-адресу. В нашем случае требуется привязать домен myproject.loc к локальному IP-адресу 127.0.0.1. После этого когда в операционной системе будет происходить обращение к myproject.loc она будет перенаправлять запросы на локальный адрес, где их будет ждать наш веб-сервер.
Настройка /etc/hosts в MacOS и Linux
В системах MacOS и Linux этот файл располагается именно по этому пути – /etc/hosts
Для его редактирования в MacOS и Linux откройте терминал и выполните команду:
sudo nano /etc/hosts
После ввода пароля пользователя вам откроется консольный текстовый редактор nano.
Переместите курсор в конец файла и добавьте строку:
127.0.0.1 myproject.loc
После внесения изменений нужно нажать сочетание клавиш Ctrl+X, далее нажать Y, и после этого нажать Enter.
Настройка /etc/hosts в Windows
В Windows нужно нажать на кнопку с логотипом Windows, в поиске набрать “Блокнот”, нажать по значку программы правой кнопкой мыши и выбрать “Запустить от имени администратора”. В программе нажать Файл -> Открыть и выбрать файл, расположенный по пути C:\Windows\System32\Drivers\etc\hosts
В конец файла добавить строку:
127.0.0.1 myproject.loc
После чего нажать Файл -> Сохранить.
Проверка работы виртуального хоста.
После внесенных изменений в созданной ранее папке www создайте файл index.php в любом текстовом редакторе. Впишите в него следующий код:
Теперь можете открыть ваш браузер и ввести адрес http://myproject.loc/
Если вы всё сделали правильно, вы увидите результат выполнения PHP-кода:
Поздравляю! Ваша первая (или нет?) программа только что успешно отработала! Мы увидели результат её работы. И если мы сейчас откроем исходник страницы в браузере, то там не будет нашего исходного кода. Он выполнился, а веб-сервер отдал нам готовый результат – именно так, как я рассказывал в уроке как работает PHP.
На этом конфигурация завершена. В следующем уроке мы установим и настроим самую крутую IDE для PHP-разработчика – PHPStorm.
XAMPP
XAMPP is an easy to install Apache distribution containing MariaDB, PHP, Perl and ProFTPD. It contains: Apache, MariaDB, PHP & PEAR, Perl, ProFTPD, phpMyAdmin, OpenSSL, GD, Freetype2, libjpeg, libpng, gdbm, zlib, expat, Sablotron, libxml, Ming, Webalizer, pdf class, ncurses, mod_perl, FreeTDS, gettext, mcrypt, mhash, eAccelerator, SQLite and IMAP C-Client.
Installation
Install the xampp AUR package.
Configuration
The default configuration should work out of the box. Setting the individual parts of XAMPP can by made by editing following files:
- /opt/lampp/etc/httpd.conf — Apache configuration. For example you can change folder with web page’s source files.
- /opt/lampp/etc/php.ini — PHP configuration.
- /opt/lampp/phpmyadmin/config.inc.php — phpMyAdmin configuration.
- /opt/lampp/etc/proftpd.conf — ProFTPD configuration.
- /opt/lampp/etc/my.cnf — MySQL configuration.
If you would like to set up security of server, just run
# /opt/lampp/xampp security
You will be asked step by step to choose passwords for web page’s access, user “pma” for phpMyAdmin, user “root” for MySQL and user “daemon” for ProFTPD.
Usage
Use the following commands to control XAMPP:
# /opt/lampp/xampp start,stop,restart
Alternatively, you can start, stop, or restart xampp.service .
Autostart on boot
In order to start XAMPP at boot, enable xampp.service .
Tips and tricks
Hosting files outside the htdocs directory
The document root (web root) directory is located at /opt/lampp/htdocs/ . All files placed in this directory will be processed by the web server.
To host other files on your system with XAMPP, you can configure an alias with Apache.
- Edit Apache’s /opt/lampp/etc/httpd.conf with your favorite editor.
- Find DocumentRoot , you will see something like:
DocumentRoot "/opt/lampp/htdocs". .
- In the next line after paste this:
yourDirectory/"> Options Indexes FollowSymLinks ExecCGI Includes AllowOverride All Require all granted
- And before the paste this:
Alias /yourAlias /yourDirectory/
. . User daemon Group daemon
- And change the daemon with yourUser and yourGroup :
User yourUser Group yourGroup
- Now do not forget to restart Apache:
# /opt/lampp/xampp restart
This will allow you to host files from your home directory (or any other directory) with XAMPP.
In the above example, you can access the files by pointing your web browser to localhost/yourAlias .
Debugging and profiling with Xdebug and XAMPP
You must first download the XAMPP Development Tools from the same download page, https://www.apachefriends.org/en/xampp-linux.html [dead link 2022-09-23 ⓘ] .
Extract this into your XAMPP directory:
# tar xvfz xampp-linux-devel-x.x.x.tar.gz -C /opt
You should be able to successfully run /opt/lampp/bin/phpize in your xdebug folder.
Local test server security
Apache, MySQL and ProFTPD can be configured so that they only listen to requests from your own computer. For most test systems this is fine and it greatly reduces the risk because the services are not reachable from the Internet.
Before you start XAMPP for the first time find and edit these files:
For Apache edit the files /opt/lampp/etc/httpd.conf and /opt/lampp/etc/extra/httpd-ssl.conf . Look for lines starting with “Listen” such as
Listen 80
and replace them with
Listen 127.0.0.1:80
For MySQL open the file /opt/lampp/etc/my.cnf find the section “[mysqld]” and add this line
bind-address=localhost
For ProFTPD, add the following lines to /opt/lampp/etc/proftpd.conf under the “DefaultServer” section
DefaultAddress 127.0.0.1 SocketBindTight on
After starting the services, verify the result by going to a command window and start and execute:
$ ss -tln
The local address column should always start with 127.0.0.1 or ::1, never with 0.0.0.0.
Manual installation
To install XAMPP manually instead of following #Installation, download the installer from the website, make it executable and run it by typing:
# ./xampp-linux-x64-version-installer.run
Note: The libxcrypt-compat , net-tools and inetutils packages are required dependencies, so make sure they are installed before launching XAMPP.
Tip: By default the installer uses the Qt backend for its UI. If you want it to use the GTK backend instead, launch:
# ./xampp-linux-x64-version-installer.run --mode gtk
If you do not want to use any graphical interface and prefer to install XAMPP directly from the terminal, launch:
# ./xampp-linux-x64-version-installer.run --mode text
For further options, launch as normal user:
$ ./xampp-linux-x64-version-installer.run --help
You can now create a systemd service for XAMPP:
/etc/systemd/system/xampp.service
[Unit] Description=XAMPP [Service] ExecStart=/opt/lampp/xampp start ExecStop=/opt/lampp/xampp stop Type=forking [Install] WantedBy=multi-user.target
Manual removal
If you have installed XAMPP manually you will need to remove it manually as well. Be sure to stop all XAMPP services.
# /opt/lampp/xampp stop
All the files needed by XAMPP to be installed are located in the previous /opt/lampp folder. So, to uninstall XAMPP:
# rm /etc/systemd/system/xampp.service # rm -r /opt/lampp
- Be sure to backup your files before doing this (such as files in /opt/lampp/htdocs ).
- If you created symlinks, you may need to destroy them too.
- Do not use this method if you have installed the package; uninstall the package instead.
Troubleshooting
PhpMyAdmin 403 Access Forbidden
If your http://localhost/phpmyadmin returns “403 Access Forbidden”, you need to edit the following settings in /opt/lampp/etc/extra/httpd-xampp.conf :
AllowOverride AuthConfig Limit #Order allow,deny #Allow from all Require all granted
Retrieved from “https://wiki.archlinux.org/index.php?title=XAMPP&oldid=749901”
XAMPP
An easy to install Apache distribution containing MySQL, PHP, and Perl
Brought to you by: beltranrueda, bitnami, koswalds, kvogelgesang
Downloads: 387,753 This Week
Last Update: 3 days ago
Solaris Linux Mac Windows
XAMPP is a very easy to install Apache Distribution for Linux, Solaris, Windows, and Mac OS X. The package includes the Apache web server, MySQL, PHP, Perl, a FTP server and phpMyAdmin.
Features
- Apache
- MySQL
- PHP
- Perl
- and many more.
Project Samples
Project Activity
Categories
License
GNU General Public License version 2.0 (GPLv2)
Follow XAMPP
Other Useful Business Software
LibreOffice is a free and powerful open source office suite.
LibreOffice is a free and powerful office suite. Word processor, spreadsheet, presentations, diagrams, databases, formula editors, charts, and more. Compatible with Windows, Mac, and Linux.
Rate This Project
User Ratings
4.6 out of 5 stars
ease 1 of 5 2 of 5 3 of 5 4 of 5 5 of 5 4 / 5
features 1 of 5 2 of 5 3 of 5 4 of 5 5 of 5 4 / 5
design 1 of 5 2 of 5 3 of 5 4 of 5 5 of 5 4 / 5
support 1 of 5 2 of 5 3 of 5 4 of 5 5 of 5 3 / 5
User Reviews
Filter Reviews:
jaochai Posted 2023-02-17
An essential program that I use regularly.
bahdenkurdish Posted 2022-12-20
jayy22 Posted 2022-12-15
Fa schifo, è inutile, datevi all’ippica. Se potessi dare meno di 1 stella, l’avrei sicuramente fatto.
makeeover Posted 2022-12-02
1 user found this review helpful.
sern2002 Posted 2022-11-24
Please fix the problem of can’t run MySQL, every month I have to reinstall it at least once. This time, I reinstalled the application and accidentally delete my docs as well and all my progress has lost. Please create a folder outside instead of putting inside!
Additional Project Details
Languages
English, German
Intended Audience
Information Technology, Education, System Administrators, Developers
User Interface
Win32 (MS Windows), Web-based, Non-interactive (Daemon)
Programming Language
Registered
Similar Business Software
AWebServer will let you share your files from your phone to any device or computer easily. You can explore the files with any SO or browser through wireless. AWebServer is an easy and friendly solution to publish your own web in your Android device with PHP and all the features that Apache.
BlueOnyx is a Linux distribution (based on CentOS and/or Scientific Linux) that aims at delivering a turnkey server appliance for web hosting. It comes with a web-based GUI interface that allows you (and your email, FTP and web hosting clients!) to manage most aspects of the server, its sites.
Easy and automatic installation, everything is pre-configured, low memory consumption, low CPU usage, capable of serving requests simultaneously, not need of root access though you can use root as well, and completely free of charge along with no advertisement. This is the best Android web.
Comments are closed, but trackbacks and pingbacks are open.