Linux debian php mysql

Linux debian php mysql

Раздел содержит информацию и подсказки, относящиеся к установке 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 install php-common libapache2-mod-php php-cli

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

Читайте также:  Type object to int python

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

# /etc/init.d/apache2 stop # /etc/init.d/apache2 start

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

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

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

# apt-cache search php # apt search php | grep -i mysql # aptitude search php

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

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

# apt install php-mysql php-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

cp php.ini-development ~/bin/php-latest/lib/

cd ~/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

cd ~/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

Источник

How to install Apache, PHP and MySQL on Debian 12 or 11

Combined Apache, PHP, and MySQL create a basic but popular web development stack known as LAMP (Linux, Apache, MySQL, PHP). This open-source stack is widely used for building PHP-based web applications and websites. In this, article we will discuss the commands used to install the LAMP server on Debian 12 Bookworm or 11 Bullseye.

LAMP comprises a Linux OS running Apache, PHP, and MySQL. Apache is a popular open-source web server managing millions of websites to deliver content over the Internet. It is highly scalable web server software with support for multiple operating systems, such as Linux, Windows, and macOS.

Whereas PHP (Hypertext Preprocessor) is not some unknown programming server-side scripting language, instead it has been used by most web developers around the globe. Often developers used it in combination with a web server such as Apache, Nginx, and more.

Further, PHP language apps can interact with various database systems to store data including MySQL or MariaDB. Well, MySQL is also an open-source relational database management system (RDBMS) widely used to store data for web applications, content management systems (CMS), and e-commerce websites.

1. Update the Debian 12 or 11 Server

The first step you should follow on the Debian server or desktop is to make sure the system is up to date. Therefore, on your command terminal run the given command which refreshes the APT package index cache as well.

sudo apt update && sudo apt upgrade -y

2. Install the Apache Web server

Next, we will install the Apache web server packages that are available to download using the default APT package manager of both Debian 12 and 11.

3. Start and Enable Apache Service

After completing the installation process, let’s start and also enable the Apache service so that it can start automatically every time we reboot our system or in case it gets crashed.

sudo systemctl start apache2
sudo systemclt enable apache2

To confirm the service status, use:

4. Install PHP on Debian 12 or 11

The default version of PHP to install on Debian would not be the latest one. For example, while doing this article, for Bookworm version 12 the PHP was 8.2, and for 11 Bullseye- PHP7.4.

So, if you want to go for the system’s default PHP versions, then you just need to run:

Whereas common PHP extensions can use:

(optional) Now, if you want to have the latest available version of PHP, if not available on your Debian then use a third-party repository called Sury.

Download GPG key

sudo wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg

Add the Sury.org repository.

sudo sh -c 'echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list'

Run system update

After that run the default command we have shown at the beginning of this step.

5. Install MySQL/MariaDB Server

Those who want the complete stack of LAMP servers also have to install MYSQL or MariaDB. And to do that we need to execute the command as mentioned below:

Unfortunately, MySQL is not available by default to install from the Debian 11 and 12 repositories, therefore, first, we need to configure it manually. See our article: How to install MySQL on Debian 11 or 12.

However, we recommend using MariaDB because it is a fork of MySQL and works exactly like MySQL.

sudo apt install mariadb-server

Other Articles:

Источник

LAMP, Linux Apache MySQL PHP

Before starting the installation, make sure your distribution is up to date (the ‘#’ indicates that you should do this as root):

MariaDB

Next install MariaDB using the following command:

# apt install mariadb-server mariadb-client

Immediately after you have installed the MariaDB server, you should run the next command to secure your installation.

# mysql_secure_installation

The previous script change root password and make some other security improvements.

You must never use your root account and password when running databases. The root account is a privileged account which should only be used for admin procedures. You will need to create a separate user account to connect to your MariaDB databases from a PHP script. You can add users to a MariaDB database by using a control panel like phpMyAdmin to easily create or assign database permissions for users.

apache2

The web server can be installed as follows:

# apt install apache2 apache2-doc

Configuring user directories for Apache Web Server

Configure Apache module userdir in /etc/apache2/mods-enabled/userdir.conf as follows:

 UserDir public_html UserDir disabled root AllowOverride All Options MultiViews Indexes SymLinksIfOwnerMatch Order allow,deny Allow from all Order deny,allow Deny from all  

From apache 2.4 and later use instead:

 UserDir public_html UserDir disabled root AllowOverride All Options MultiViews Indexes SymLinksIfOwnerMatch Require all granted Require all denied  

Create directory as user (not as root):

$mkdir /home/$USER/public_html

Change group as root (substitute your username) and restart web server:

# chgrp www-data /home//public_html # service apache2 restart

If you get a Forbidden error when accessing home folder through Apache check /home/username has permissions drwxr-xr-x. If the permissions are wrong correct them as such:

To be able to serve PHP (PHP needs to be installed as per instructions) check that /etc/apache2/mods-available/php5.conf is correct:

  SetHandler application/x-httpd-php Require all granted SetHandler application/x-httpd-php-source Require all denied # To re-enable php in user directories comment the following lines # (from to .) Do NOT set it to On as it # prevents .htaccess files from disabling it. # # # php_admin_value engine Off # # 

Place some web content in ~/public_html and see the results at http://localhost/~username

The «P» part

Installing the PHP subset of LAMP in Debian is quite simple, you just type this as root in an console (the # is the root prompt symbol):

If you prefer Perl, then you might consider:

# apt install perl libapache2-mod-perl2

If you prefer Python, then you might consider:

# apt install python3 libapache2-mod-python

Configuration

Apache2 configuration file: /etc/apache2/apache2.conf

You can edit this file when needed, but for most simple applications, this should not be necessary as most stuff is now done using conf.d.

Test PHP

To test the PHP interface, edit the file /var/www/html/test.php:

and insert the following code.

Afterwards, point your browser to http:///test.php to start using it.

phpMyAdmin

Probably you also want to install phpMyAdmin for easy configuration:

To have access to phpMyAdmin on your website (i.e. http://example.com/phpmyadmin/ ) all you need to do is include the following line in /etc/apache2/apache2.conf (needed only before Squeeze, since 6.0 it will be linked by the package install script to /etc/apache2/conf.d/phpmyadmin.conf -> ../../phpmyadmin/apache.conf automatically):

Include /etc/phpmyadmin/apache.conf

Go to http:///phpmyadmin/ to start using it. (Use the IP or name of your PC/server instead of (The localhost IP is always 127.0.0.1).)

PHP: /etc/php5/apache2/php.ini

A usual issue with PHP configuration is to enable MySQL. Just edit the file and uncomment the following line (tip: search for mysql)

Note that this should not be needed anymore as conf.d is now used.

MySQL : /etc/mysql/my.cnf

You can find configuration examples in /usr/share/doc/mysql-server/examples

Источник

Оцените статью