Configure php in linux

Apache NetBeans 12.5

Last reviewed on 2019-02-02

This tutorial shows how to configure the PHP development environment in the Ubuntu operating system (7.10 and later). This involves installing and configuring the PHP engine, a MySQL database, an Apache web server, and the XDebug debugger.

Requirements

To follow this tutorial, you need the following software and resources.

Apache HTTP Server 2.2 is recommended.

A database server

MySQL Server 5.0 is recommended.

A PHP debugger (optional)

XDebug 2.0 or later

Typically, development and debugging is performed on a local web server, while the production environment is located on a remote web server. Setting up a remote web server is described in + Deploying a PHP Application on a Remote Web Server Using the NetBeans IDE+. This tutorial has you set up a local web server. PHP support can be added to a number of local web servers (IIS, Xitami, and so on), but most commonly Apache HTTP Server is used.

Installing the Software

This tutorial shows how to configure the PHP development environment in Ubuntu 7.04 and later. You need to:

Install the Apache2 HTTP server, the PHP5 engine, the MySQL 5.0 database server, and the PHP5-MySQL module. These packages can be installed together as the LAMP stack, or they can be installed separately.

See the Ubuntu community for more information on installing Apache, MySQL, and PHP.

Installing the Software Packages Together

Ubuntu provides a Linux AMP (LAMP) package that contains all the necessary packages for your PHP environment. You can install the software by executing the following command at the command prompt in the Terminal window:

The lamp-server package includes the most suitable version of PHP, Apache 2, MySQL, and PHP5-MySQL.

Installing the Software Packages Separately

Instead of installing the entire set of LAMP packages, you can also install the packages individually. This is useful if you already have installed one of the components, such as the Apache server or MySQL database server. You can use command-line tools or the Synaptic Package Manager GUI.

The individual packages to install are the following:

Checking the Installation

After you set up your PHP web stack, check that it is installed correctly and that your Apache server recognizes your PHP engine.

To check that Apache and PHP are installed and running, open NetBeans IDE and create a PHP project. In the index.php file, enter the PHP method phpinfo() . Run the file. The standard PHP information page should display.

Troubleshooting

The following are some frequently encountered problems when checking the installation of your PHP stack in Ubuntu:

The browser window displays a Not Found error for

USER/PROJECT/index.php . Remove the

USER string from the URL. For example, if this error appears for the URL

ubuntu/test1/index.php , change the URL to test1/index.php . Note that you can set the URL for a PHP project in NetBeans IDE either when you create the project, or by right-clicking the project node and going to Properties > Run Configuration.

The browser shows you a popup asking you to open the file, as if the PHP engine is not recognized. There’s a problem with your php5-common package. Replace it with php5 and phpmyadmin . To replace php5-common , run the following two commands:

Specifying the Document Root for the Apache2 HTTP Server

The Document Root is the directory where the Apache HTTP server takes files for displaying in the browser. The Document Root is specified in the file that defines your virtual host. The default virtual host configuration file is

with the document root

We recommend that you create your own virtual host and enable it instead of editing the default one.

Creating the Document Root Location

Choose Places > Home Folder.

From the context menu, choose Create Folder.

Enter the name of the folder, for example, public_html.

Creating a New Virtual Host

To launch the Terminal, choose Applications > Accessories > Terminal. The Terminal window opens.

To copy the configuration file of the default virtual host to a new file ( mysite ), type the following command at the command prompt:

Run the gedit application and edit the new configuration file ( mysite ) in it:

If asked, enter the password that you specified for the root user during the installation of your operating system.

Change the Document Root to point to the new location:

Источник

Installation on Unix systems

Table of Contents

This section will guide you through the general configuration and installation of PHP on Unix systems. Be sure to investigate any sections specific to your platform or web server before you begin the process.

As our manual outlines in the General Installation Considerations section, we are mainly dealing with web centric setups of PHP in this section, although we will cover setting up PHP for command line usage as well.

There are several ways to install PHP for the Unix platform, either with a compile and configure process, or through various pre-packaged methods. This documentation is mainly focused around the process of compiling and configuring PHP. Many Unix like systems have some sort of package installation system. This can assist in setting up a standard configuration, but if you need to have a different set of features (such as a secure server, or a different database driver), you may need to build PHP and/or your web server. If you are unfamiliar with building and compiling your own software, it is worth checking to see whether somebody has already built a packaged version of PHP with the features you need.

Prerequisite knowledge and software for compiling:

  • Basic Unix skills (being able to operate «make» and a C compiler)
  • An ANSI C compiler
  • A web server
  • Any module specific components (such as GD , PDF libs, etc.)

When building directly from Git sources or after custom modifications you might also need:

  • autoconf: 2.59+ (for PHP >= 7.0.0), 2.64+ (for PHP >= 7.2.0)
  • automake: 1.4+
  • libtool: 1.4.x+ (except 1.4.2)
  • re2c: 0.13.4+
  • bison:
    • PHP 7.0 — 7.3: 2.4 or later (including Bison 3.x)
    • PHP 7.4: > 3.0

The initial PHP setup and configuration process is controlled by the use of the command line options of the configure script. You could get a list of all available options along with short explanations running ./configure —help. Our manual documents the different options separately. You will find the core options in the appendix, while the different extension specific options are described on the reference pages.

When PHP is configured, you are ready to build the module and/or executables. The command make should take care of this. If it fails and you can’t figure out why, see the Problems section.

Some Unix systems (such as OpenBSD and SELinux) may disallow mapping pages both writable and executable for security reasons, what is called PaX MPROTECT or W^X violation protection. This kind of memory mapping is, however, necessary for PCRE’s JIT support, so either PHP has to be built without PCRE’s JIT support, or the binary has to be whitelisted by any means provided by the system.

Note: Cross-compiling for ARM with the Android toolchain is currently not supported.

Источник

Apache NetBeans 12.5

Software or Resource Version Required
This tutorial needs a review. You can open a JIRA issue, or edit it in GitHub following these contribution guidelines.

В данном учебном курсе рассматривается процедура настройки среды разработки PHP в операционной системе Ubuntu (версия 7.10 и более поздние). Эта процедура предполагает установку и настройку механизма PHP, базы данных MySQL, веб-сервера Apache и отладчика XDebug.

Для работы с этим учебным курсом требуется следующее программное обеспечение и ресурсы.

Пакет загрузки PHP

Рекомендуется использовать HTTP-сервер Apache 2.2.

Сервер базы данных

Рекомендуется использовать сервер MySQL 5.0.

Отладчик PHP (не обязательно)

Версия XDebug 2.0 или более поздняя

Как правило, разработка и отладка выполняются на локальном веб-сервере, в то время как производственная среда размещена на удаленном веб-сервере. Настройка удаленного веб-сервера описана в разделе + Развертывание приложения PHP на удаленном веб-сервере с помощью IDE NetBeans+. Этот учебный курс содержит информацию, необходимую для настройки локального веб-сервера. Поддержка PHP может добавляться к целому ряду локальных веб-серверов (IIS, Xitami и т.д.), но обычно используется сервер HTTP Apache.

Установка программного обеспечения

В данном учебном курсе рассматривается процедура настройки среды разработки PHP в операционной системе Ubuntu (версия 7.04 и более поздние). Необходимо выполнить следующие действия:

Установить сервер Apache2 HTTP, механизм PHP5, сервер базы данных MySQL 5.0 и модуль PHP5-MySQL. Эти пакеты можно установить одновременно как стек LAMP или установить по отдельности.

Для получения дополнительных сведений об установке Apache, MySQL и PHP см. Сообщество Ubuntu.

Одновременная установка всех пакетов программного обеспечения

Ubuntu предоставляет пакет Linux AMP (LAMP), который содержит все необходимые пакеты для среды PHP. Для установки программного обеспечения можно выполнить следующую команду в командной строке в окне терминала:

Пакет lamp-server включает в себя наиболее удобную версию PHP, Apache 2, MySQL и PHP5-MySQL.

Установка пакетов программного обеспечения по отдельности

Вместо установки целого набора коллекций LAMP пакеты можно также установить индивидуально. Эта функция используется, если один из компонентов (например, сервер Apache или сервер базы данных MySQL) уже установлен. Можно использовать средства командной строки или графический пользовательский интерфейс Synaptic Package Manager.

Отдельно могут быть установлены следующие пакеты:

Проверка установки

После настройки пакета PHP Web Stack убедитесь в том, что он установлен правильно, а сервер Apache распознает механизм PHP.

Чтобы убедиться, что Apache и PHP установлены и запущены, откройте IDE NetBeans и создайте проект PHP. В файле index.php введите метод PHP phpinfo() . Запустите файл. При этом должна отобразиться стандартная информационная страница PHP.

Устранение проблем

Ниже перечислены часто возникающие проблемы при проверке установки стека PHP в Ubuntu:

*В окне браузера отображается ошибка «Not Found» для

USER/PROJECT/index.php *. Удалите строку

USER из URL-адреса. Например, если эта ошибка происходит для URL-адреса

ubuntu/test1/index.php , измените его на test1/index.php . Обратите внимание, что можно настроить адрес URL для проекта PHP в IDE NetBeans либо при создании проекта или путем щелчка правой кнопки мыши узла проекта и перехода в ‘Свойства’ > ‘Запустить конфигурацию’.

В браузере отображается всплывающее окно с запросом на открытие файла, как если бы механизм PHP не распознавался. Пакет php5-common содержит ошибку. Замените его пакетами php5 и phpmyadmin . Для замены пакета php5-common необходимо выполнить следующие две команды:

Указание корневого узла документа для сервера HTTP Apache2

Корневой узел документов представляет собой папку, из которой сервер HTTP Apache извлекает файлы для отображения в браузере. Корневой узел документов указан в файле, определяющем виртуальный узел. Файл настройки, определяющий виртуальный узел по умолчанию:

с корневым узлом документов

Вместо изменения узла по умолчанию рекомендуется создать и активировать собственный виртуальный узел.

Создание местоположения корневого узла документов

Выберите «Places > Home Folder».

В контекстном меню выберите «Create Folder».

Введите имя папки, например public_html.

Создание нового виртуального узла

Для запуска терминала выберите «Applications>Accessories>Terminal». Откроется окно терминала.

Для копирования файла настройки из виртуального узла по умолчанию в новый файл ( mysite ) введите в командной строке следующую команду:

Запустите приложение gedit и отредактируйте в нем новый файл настройки ( mysite ):

При появлении запроса введите пароль, определенный для пользователя root во время установки операционной системы.

Измените корневой узел документов, указав в нем новое местоположение:

Источник

Configure php in linux

Раздел содержит информацию и подсказки, относящиеся к установке PHP на » Debian GNU/Linux.

Неофициальные сборки от третьих лиц не поддерживаются. О любых ошибках следует сообщать разработчикам Debian, но перед этим стоит проверить, возможно они уже исправлены в новых релизах, которые можно скачать на » странице загрузки.

Хотя и существует универсальная инструкция по установке PHP на Unix/Linux, в этом разделе мы рассмотрим особенности специфичные для Debian, такие как использование команд apt или aptitude . В рамках этого руководства обе эти команды рассматриваются как взаимозаменяемые.

Использование APT

Во первых, обратите внимание на то, что некоторые пакеты связаны: libapache-mod-php нужен для интеграции с Apache 2, и php-pear с PEAR.

Во-вторых, перед установкой убедитесь, что список пакетов находится в актуальном состоянии. Как правило, это делается с помощью команды apt update.

Пример #1 Пример установки Apache 2 на Debian

APT автоматически установит модуль PHP для Apache 2 и все их зависимости и, затем, активирует их. Apache должен быть перезапущен для того, чтобы изменения вступили в силу. Например:

Пример #2 Остановка и запуск Apache после установки PHP

Контроль конфигурации

Изначально, PHP устанавливается только с основными модулями ядра. Если вы хотите установить дополнительные модули, такие как MySQL, cURL, GD и т.д., это также можно сделать с помощью команды apt .

Пример #3 Способы получить список дополнительных пакетов PHP

Будет выведен список большого числа пакетов, включая несколько специфичных, таких как php-cgi, php-cli and php-dev. Определите, какие вам нужны и установите с помощью apt-get или aptitude . И, так как Debian производит проверку зависимостей, вам будет выведен запрос на их установку.

Пример #4 Установка PHP с MySQL и cURL

APT автоматически добавит необходимые строки в соответствующие php.ini , /etc/php/7.4/php.ini , /etc/php/7.4/conf.d/*.ini , и т.д. В зависимости от модуля, будут внесены записи типа extension=foo.so . В любом случае, чтобы эти изменения вступили в силу, необходимо будет перезапустить сервер веб-сервер.

Стандартные проблемы

  • Если скрипты PHP не разбираются веб-сервером, то скорее всего это означает, что PHP не был добавлен в конфигурацию веб-сервера. На Debian это обычно /etc/apache2/apache2.conf или похожий. Смотрите документацию Debian для выяснения подробностей.
  • Модуль, по-видимому, установлен, а его функции всё равно не распознаются. В таком случае убедитесь, что соответствующий ini-файл был загружен и/или веб-сервер был перезагружен после установки модуля.
  • Для установки пакетов в Debian существуют две основных команды (не считая стандартных вариантов Linux): apt и aptitude . Объяснения их синтаксиса, особенностей и отличий друг от друга выходит за рамки данного руководства.

User Contributed Notes 6 notes

To refresh this document, perhaps it would be worth mentioning more modern methods to serve php content under apache httpd.

Specifically, the preferred method is now fastcgi, using either of those recipes:

While the legacy mod_php approach is still applicable for some older installations, the fastcgi method is much faster, and require much less RAM to operate, based on similar traffic patterns.

Compiling PHP on Ubuntu boxes.

If you would like to compile PHP from source as opposed to relying on package maintainers, here’s a list of packages, and commands you can run

STEP 1:
sudo apt-get install autoconf build-essential curl libtool \
libssl-dev libcurl4-openssl-dev libxml2-dev libreadline7 \
libreadline-dev libzip-dev libzip4 nginx openssl \
pkg-config zlib1g-dev

So you don’t overwrite any existing PHP installs on your system, install PHP in your home directory. Create a directory for the PHP binaries to live

STEP 2:
# download the latest PHP tarball, decompress it, then cd to the new directory.

STEP 3:
Configure PHP. Remove any options you don’t need (like MySQL or Postgres (—with-pdo-pgsql))

./configure —prefix=$HOME/bin/php-latest \
—enable-mysqlnd \
—with-pdo-mysql \
—with-pdo-mysql=mysqlnd \
—with-pdo-pgsql=/usr/bin/pg_config \
—enable-bcmath \
—enable-fpm \
—with-fpm-user=www-data \
—with-fpm-group=www-data \
—enable-mbstring \
—enable-phpdbg \
—enable-shmop \
—enable-sockets \
—enable-sysvmsg \
—enable-sysvsem \
—enable-sysvshm \
—enable-zip \
—with-libzip=/usr/lib/x86_64-linux-gnu \
—with-zlib \
—with-curl \
—with-pear \
—with-openssl \
—enable-pcntl \
—with-readline

STEP 4:
compile the binaries by typing: make

If no errors, install by typing: make install

STEP 5:
Copy the PHP.ini file to the install directory

/bin/php-latest/etc;
mv php-fpm.conf.default php-fpm.conf
mv php-fpm.d/www.conf.default php-fpm.d/www.conf

STEP 7:
create symbolic links for your for your binary files

/bin
ln -s php-latest/bin/php php
ln -s php-latest/bin/php-cgi php-cgi
ln -s php-latest/bin/php-config php-config
ln -s php-latest/bin/phpize phpize
ln -s php-latest/bin/phar.phar phar
ln -s php-latest/bin/pear pear
ln -s php-latest/bin/phpdbg phpdbg
ln -s php-latest/sbin/php-fpm php-fpm

STEP 8: link your local PHP to the php command. You will need to logout then log back in for php to switch to the local version instead of the installed version

# add this to .bashrc
if [ -d «$HOME/bin» ] ; then
PATH=»$HOME/bin:$PATH»
fi

Источник

Читайте также:  Кто пишет ядро линукс
Оцените статью
Программное обеспечение или материал Требуемая версия