Как установить php на linux
This section contains notes and hints specific to installing PHP on » Debian GNU/Linux.
Warning
Unofficial builds from third-parties are not supported here. Any bugs should be reported to the Debian team unless they can be reproduced using the latest builds from our » download area.
While the instructions for building PHP on Unix apply to Debian as well, this manual page contains specific information for other options, such as using either the apt or aptitude commands. This manual page uses these two commands interchangeably.
Using APT
First, note that other related packages may be desired like libapache-mod-php to integrate with Apache 2, and php-pear for PEAR.
Second, before installing a package, it’s wise to ensure the package list is up to date. Typically, this is done by running the command apt update.
Example #1 Debian Install Example with Apache 2
# apt install php-common libapache2-mod-php php-cli
APT will automatically install the PHP module for Apache 2 and all of its dependencies, and then activate it. Apache should be restarted in order for the changes take place. For example:
Example #2 Stopping and starting Apache once PHP is installed
# /etc/init.d/apache2 stop # /etc/init.d/apache2 start
Better control of configuration
In the last section, PHP was installed with only core modules. It’s very likely that additional modules will be desired, such as MySQL, cURL, GD, etc. These may also be installed via the apt command.
Example #3 Methods for listing additional PHP packages
# apt-cache search php # apt search php | grep -i mysql # aptitude search php
The examples will show a lot of packages including several PHP specific ones like php-cgi, php-cli and php-dev. Determine which are needed and install them like any other with either apt or aptitude . And because Debian performs dependency checks, it’ll prompt for those so for example to install MySQL and cURL:
Example #4 Install PHP with MySQL, cURL
# apt install php-mysql php-curl
APT will automatically add the appropriate lines to the different php.ini related files like /etc/php/7.4/php.ini , /etc/php/7.4/conf.d/*.ini , etc. and depending on the extension will add entries similar to extension=foo.so . However, restarting the web server (like Apache) is required before these changes take affect.
Common Problems
- If the PHP scripts are not parsing via the web server, then it’s likely that PHP was not added to the web server’s configuration file, which on Debian may be /etc/apache2/apache2.conf or similar. See the Debian manual for further details.
- If an extension was seemingly installed yet the functions are undefined, be sure that the appropriate ini file is being loaded and/or the web server was restarted after installation.
- There are two basic commands for installing packages on Debian (and other linux variants): apt and aptitude . However, explaining the subtle differences between these commands goes beyond the scope of this manual.
User Contributed Notes 6 notes
10 years ago
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.
5 years ago
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
mkdir -p ~/bin/php7-latest/
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 Linux, Apache, MySQL, PHP (LAMP) Stack on Ubuntu 22.04
A “LAMP” stack is a group of open source software that is typically installed together in order to enable a server to host dynamic websites and web apps written in PHP. This term is 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, you’ll set up a LAMP stack on an Ubuntu 22.04 server.
1-click deploy a database using DigitalOcean Managed Databases. Let DigitalOcean focus on scaling, maintenance, and upgrades for your database.
Prerequisites
In order to complete this tutorial, you will need to have an Ubuntu 22.04 server with a non-root sudo -enabled user account and a basic firewall. This can be configured using our initial server setup guide for Ubuntu 22.04.
Step 1 — Installing Apache and Updating the Firewall
The Apache web server is among the most popular web servers in the world. It’s well documented, has an active community of users, and has been in wide use for much of the history of the web, which makes it a great choice for hosting a website.
Start by updating the package manager cache. If this is the first time you’re using sudo within this session, you’ll be prompted to provide your user’s password to confirm you have the right privileges to manage system packages with apt :
Then, install Apache with:
You’ll be prompted to confirm Apache’s installation. Confirm by pressing Y , then ENTER .
Once the installation is finished, you’ll need to adjust your firewall settings to allow HTTP traffic. Ubuntu’s default firewall configuration tool is called Uncomplicated Firewall (UFW). It has different application profiles that you can leverage. To list all currently available UFW application profiles, execute this command:
OutputAvailable applications: Apache Apache Full Apache Secure OpenSSH
Here’s what each of these profiles mean:
- Apache: This profile opens only port 80 (normal, unencrypted web traffic).
- Apache Full: This profile opens both port 80 (normal, unencrypted web traffic) and port 443 (TLS/SSL encrypted traffic).
- Apache Secure: This profile opens only port 443 (TLS/SSL encrypted traffic).
For now, it’s best to allow only connections on port 80 , since this is a fresh Apache installation and you don’t yet have a TLS/SSL certificate configured to allow for HTTPS traffic on your server.
To only allow traffic on port 80 , use the Apache profile:
Verify the change with:
OutputStatus: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere Apache ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) Apache (v6) ALLOW Anywhere (v6)
Traffic on port 80 is now allowed through the firewall.
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 (view 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
The default Ubuntu 22.04 Apache web page is there for informational and testing purposes. Below is an example of the Apache default web page:
If you can view this page, your web server is 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 to 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:
Whichever method you choose, type in your IP address into your web browser to verify that your server is running.
Step 2 — Installing MySQL
Now that you have a web server up and running, you need to install the database system to be able to store and manage data for your site. MySQL is a popular database management system used within PHP environments.
Again, use apt to acquire and install this software:
When prompted, confirm installation by typing Y , and then ENTER .
When the installation is finished, it’s recommended that you run a security script that comes pre-installed with MySQL. This script will remove some insecure default settings and lock down access to your database system.
Warning: As of July 2022, an error will occur when you run the mysql_secure_installation script without some further configuration. The reason is that this script will attempt to set a password for the installation’s root MySQL account but, by default on Ubuntu installations, this account is not configured to connect using a password.
Prior to July 2022, this script would silently fail after attempting to set the root account password and continue on with the rest of the prompts. However, as of this writing the script will return the following error after you enter and confirm a password:
Output . Failed! Error: SET PASSWORD has no significance for user 'root'@'localhost' as the authentication method used doesn't store authentication data in the MySQL server. Please consider using ALTER USER instead if you want to change authentication parameters. New password:
This will lead the script into a recursive loop which you can only get out of by closing your terminal window.
Because the mysql_secure_installation script performs a number of other actions that are useful for keeping your MySQL installation secure, it’s still recommended that you run it before you begin using MySQL to manage your data. To avoid entering this recursive loop, though, you’ll need to first adjust how your root MySQL user authenticates.
First, open up the MySQL prompt:
Then run the following ALTER USER command to change the root user’s authentication method to one that uses a password. The following example changes the authentication method to mysql_native_password :
After making this change, exit the MySQL prompt:
Following that, you can run the mysql_secure_installation script without issue.
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. 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:
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 doesn’t involve using a password, even when one is set, you should define a strong password here as an additional safety measure.
If you 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 continue with that password. If you are happy with your current password, enter Y for “yes” at the prompt:
Estimated strength of the password: 100 Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : y
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 whether 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. Below is an example output:
OutputWelcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 10 Server version: 8.0.28-0ubuntu4 (Ubuntu) Copyright (c) 2000, 2022, 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 seem like a security concern, 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.
Note: There are some older versions of PHP that doesn’t support caching_sha2_password , the default authentication method for MySQL 8. For that reason, when creating database users for PHP applications on MySQL 8, you may need to configure your application to use the mysql_native_password plug-in instead. This tutorial will demonstrate how to do that in Step 6.
Your MySQL server is now installed and secured. Next, you’ll install PHP, the final component in the LAMP stack.
Step 3 — Installing PHP
You have Apache installed to serve your content and MySQL installed to store and manage your data. PHP is the component of our setup that will process code to display dynamic content to the final user. In addition to the php package, you’ll need php-mysql , a PHP module that allows PHP to communicate with MySQL-based databases. You’ll also need libapache2-mod-php to enable Apache to handle PHP files. Core PHP packages will automatically be installed as dependencies.
To install these packages, run the following command:
Once the installation is finished, run the following command to confirm your PHP version:
OutputPHP 8.1.2 (cli) (built: Mar 4 2022 18:13:46) (NTS) Copyright (c) The PHP Group Zend Engine v4.1.2, Copyright (c) Zend Technologies with Zend OPcache v8.1.2, Copyright (c), by Zend Technologies
At this point, your LAMP stack is fully operational, but before testing your setup with a PHP script, it’s best to set up a proper Apache Virtual Host to hold your website’s files and folders.
Step 4 — Creating a Virtual Host for your Website
When using the Apache web server, you can create virtual hosts (similar to server blocks in Nginx) to encapsulate configuration details and host more than one domain from a single server. In this guide, we’ll set up a domain called your_domain, but you should replace this with your own domain name.
Note: In case you are using DigitalOcean as DNS hosting provider, check out our product documentation for detailed instructions on how to set up a new domain name and point it to your server.
Apache on Ubuntu 22.04 has one virtual host 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 , we’ll create a directory structure within /var/www for the 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 will reference your current system user:
Then, open a new configuration file in Apache’s sites-available directory using your preferred command-line editor. Here, we’ll use nano :
This will create a new blank file. Add in the following bare-bones configuration with your own domain name:
/etc/apache2/sites-available/your_domain.conf
ServerName your_domain ServerAlias www.your_domain ServerAdmin webmaster@localhost DocumentRoot /var/www/your_domain ErrorLog $/error.log CustomLog $/access.log combined
Save and close the file when you’re done. If you’re using nano , do that by pressing CTRL+X , then Y and ENTER .
With this VirtualHost configuration, we’re telling Apache to serve your_domain using /var/www/ your_domain as the web root directory. If you’d like to test Apache without a domain name, you can remove or comment out the options ServerName and ServerAlias by adding a pound sign ( # ) the beginning of each option’s lines.
Now, use a2ensite to enable the new virtual host:
You might want to disable the default website that comes installed with Apache. This is required if you’re not using a custom domain name, because in this case Apache’s default configuration would override your virtual host. To disable Apache’s default website, type:
To make sure your configuration file doesn’t contain syntax errors, run the following command:
Finally, reload Apache so these changes take effect:
Your new website is now active, but the web root /var/www/ your_domain is still empty. Create an index.html file in that location to test that the virtual host works as expected:
Include the following content in this file:
/var/www/your_domain/index.html
your_domain website Hello World!
This is the landing page of your_domain.
Save and close the file, then go to your browser and access your server’s domain name or IP address:
http://server_domain_or_IP
Your web page should reflect the contents in the file you just edited:

You can leave this file in place as a temporary landing page for your application until you set up an index.php file to replace it. Once you do that, remember to remove or rename the index.html file from your document root, as it would take precedence over an index.php file by default.
A Note About DirectoryIndex on Apache
With the default DirectoryIndex settings on Apache, a file named index.html will always take precedence over an index.php file. This is useful for setting up maintenance pages in PHP applications, by creating a temporary index.html file containing an informative message to visitors. Because this page will take precedence over the index.php page, it will then become the landing page for the application. Once maintenance is over, the index.html is renamed or removed from the document root, bringing back the regular application page.
In case you want to change this behavior, you’ll need to edit the /etc/apache2/mods-enabled/dir.conf file and modify the order in which the index.php file is listed within the DirectoryIndex directive:
/etc/apache2/mods-enabled/dir.conf
DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
After saving and closing the file, you’ll need to reload Apache so the changes take effect:
In the next step, we’ll create a PHP script to test that PHP is correctly installed and configured on your server.
Step 5 — Testing PHP Processing on your Web Server
Now that you have a custom location to host your website’s files and folders, create a PHP test script to confirm that Apache is able to handle and process requests for PHP files.
Create a new file named info.php inside your custom web root folder:
This will open a blank file. Add the following text, which is valid PHP code, inside the file:
/var/www/your_domain/info.php
phpinfo();
When you are finished, save and close the file.
To test this script, go to your web browser and access your server’s domain name or IP address, followed by the script name, which in this case is info.php :
http://server_domain_or_IP/info.php
Here is an example of the default PHP web page:
This page provides 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 see this page in your browser, then your PHP installation is working as expected.
After checking the relevant information about your PHP server through that page, it’s best to remove the file you created as it contains sensitive information about your PHP environment and your Ubuntu server. Use rm to do so:
You can always recreate this page if you need to access the information again later.
Step 6 — Testing Database Connection from PHP (Optional)
If you want to test whether PHP is able to connect to MySQL and execute database queries, you can create a test table with test data and query for its contents from a PHP script. Before you do that, you need to create a test database and a new MySQL user properly configured to access it.
Create a database named example_database and a user named example_user. You can replace these names with different values.
First, connect to the MySQL console using the root account:
To create a new database, run the following command from your MySQL console:
Now create a new user and grant them full privileges on the custom database you’ve just created.
The following command creates a new user named example_user that authenticates with the caching_sha2_password method. We’re defining this user’s password as password , but you should replace this value with a secure password of your own choosing.
Note: The previous ALTER USER statement sets the root MySQL user to authenticate with the caching_sha2_password plugin. Per the official MySQL documentation, caching_sha2_password is MySQL’s preferred authentication plugin, as it provides more secure password encryption than the older, but still widely used, mysql_native_password .
However, some versions of PHP don’t work reliably with caching_sha2_password . PHP has reported that this issue was fixed as of PHP 7.4, but if you encounter an error when trying to log in to phpMyAdmin later on, you may want to set root to authenticate with mysql_native_password instead:
Now give this user permission over the example_database database:
This will give the example_user user full privileges over the example_database database, while preventing this user from creating or modifying other databases on your server.
Now exit the MySQL shell with:
Test if the new user has the proper permissions by logging in to the MySQL console again, this time using the custom user credentials:
Notice the -p flag in this command, which will prompt you for the password used when creating the example_user user. After logging in to the MySQL console, confirm that you have access to the example_database database:
This will give you the following output:
Output+--------------------+ | Database | +--------------------+ | example_database | | information_schema | +--------------------+ 2 rows in set (0.000 sec)
Next, create a test table named todo_list. From the MySQL console, run the following statement:
Insert a few rows of content in the test table. Repeat the next command a few times, using different values, to populate your test table:
To confirm that the data was successfully saved to your table, run:
The following is the output:
Output+---------+--------------------------+ | item_id | content | +---------+--------------------------+ | 1 | My first important item | | 2 | My second important item | | 3 | My third important item | | 4 | and this one more thing | +---------+--------------------------+ 4 rows in set (0.000 sec)
After confirming that you have valid data in your test table, exit the MySQL console:
Now you can create the PHP script that will connect to MySQL and query for your content. Create a new PHP file in your custom web root directory using your preferred editor:
The following PHP script connects to the MySQL database and queries for the content of the todo_list table, exhibiting the results in a list. If there’s a problem with the database connection, it will throw an exception.
Add this content into your todo_list.php script, remembering to replace the example_user and password with your own:
/var/www/your_domain/todo_list.php
Save and close the file when you’re done editing.
You can now access this page in your web browser by visiting the domain name or public IP address configured for your website, followed by /todo_list.php :
http://your_domain_or_IP/todo_list.php
This web page should reveal the content you’ve inserted in your test table to your visitor:

That means your PHP environment is ready to connect and interact with your MySQL server.
Conclusion
In this guide, you’ve built a flexible foundation for serving PHP websites and applications to your visitors, using Apache as a web server and MySQL as a database system.
As an immediate next step, you should ensure that connections to your web server are secured, by serving them via HTTPS. In order to accomplish that, you can use Let’s Encrypt to secure your site with a free TLS/SSL certificate.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Как установить PHP 7 в Windows 10
Язык программирования PHP без труда устанавливается на Windows. Для этого создатели PHP подготовили специальную Windows-версию языка, которую можно скачать с сайта PHP.
Для среды разработки я использую PHP 7, с тем расчётом, чтобы мой код был готов к тому моменту, как PHP 7 можно будет установить на боевой сервер. Для того, чтобы установить PHP 7 в операционной системе Windows понадобится программа Visual C++ Redistributable for Visual Studio 2015, которую можно скачать с официального сайта Майкрософта. Установка этой программы не содержит никаких трудностей, нужно просто нажимать кнопку «Далее».
После установки Visual C++ Redistributable скачиваем архив PHP 7 для Windows (VC14 Non Thread Safe x64 или x86 в зависимости от разрядности системы) c официального сайта PHP. В архиве нет инсталлятора, его просто нужно распаковать в папку где-нибудь на диске. В пути к этой папке не должно быть пробелов и русских букв, у меня это просто C:\PHP.
После распаковки нужно добавить PHP в системный PATH для того, чтобы можно было запускать PHP из любого каталога:
- нажимаем win+x и переходим в настройки System;
- переходим в Advanced system settings;

- выбираем Environment Variables;

- выбираем переменну PATH и нажимаем кнопку Edit;

- нажимаем кнопку New и вводим адрес каталога с распакованным PHP, например C:\PHP;

- нажимаем кнопку Ok.
Теперь нужно настроить PHP для работы:
- переименовываем файл php.ini-production в php.ini ;
- раскоментируем (убираем знак ; ) перед строчками:
- extension=php_curl.dll ;
- extension=php_gd2.dll ;
- extension=php_mbstring.dll ;
- extension=php_openssl.dll ;
- extension=php_pdo_mysql.dll ;
- extension=php_pdo_sqlite.dll ;
- extension=php_sqlite3.dll .
Всё, PHP 7 установлен в системе и готов к использованию.
Как установить PHP 7 в Windows 10: 10 комментариев
Добрый день!
Что значит раскомментируем? это в файле php.ini?
Но в версии php 7.2 в этом файле ни одной из этих строк,
(extension=php_curl.dll;
extension=php_gd2.dll;
extension=php_mbstring.dll;
extension=php_openssl.dll;
extension=php_pdo_mysql.dll;
extension=php_pdo_sqlite.dll;
extension=php_sqlite3.dll.)
как быть?
cimmwolf :
Здравствуйте.
Да, вы правы. Теперь их нужно добавлять туда вручную. Найдите раздел Dynamic Extensions и добавьте их туда вот в таком виде:
extension=php_curl.dll
extension=php_gd2.dll
extension=php_mbstring.dll
extension=php_openssl.dll
extension=php_pdo_mysql.dll
extension=php_pdo_sqlite.dll
extension=php_sqlite3.dll
Александр Чеберко :
Всё работает. Огромное спасибо!
Здавствуйте!
Я все делал как у вас написано. Однако были некоторые нюансы. При начале установки Visual C++ Redistributable появилось сообщение, что уже установлена такая программа и установка была прекращена. Я проверил и, действительно ,установлены версии 2008, 2010,2012,2013.2017. Что в этой ситуации делать?
И еще по поводу изменения переменной PATH. Удалось ее изменить только из командной строки командой SETX с правами админа.
И, последний, может быть, наивный вопрос.
Для чего все это делается? Ну, кликну я по файлу с расширением PHP, и что получу в итоге? Ведь здесь никакого отладчика нет.
Если Вас не затруднит мое обращение, то ответьте, пожалуйста.
С уважением, Петр
cimmwolf :
Всё это делается только для того, чтобы можно было запускать PHP-программы в среде Windows.
extension=curl
теперь это так называется?
Добавлять не надо?
cimmwolf :
Да, теперь PHP рекомендует указывать расширения так как вы указали. Вот выдержка из их рекомендации:
The syntax used in previous PHP versions (‘extension=.so’ and ‘extension=’php_.dll’) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (‘extension=) syntax.
Вероника :
Если Visual C++ Redistributable for Visual Studio новее 15 года, это критично для установки ПХП?
cimmwolf :
В посте немного устаревшая информация. Я думаю, что с более новыми версиями всё тоже должно заработать, попробуйте
extension=php_curl.dll
+++
extension=php_gd.dll
+++
extension=php_mbstring.dll
extension=php_openssl.dll
extension=php_pdo_mysql.dll
extension=php_pdo_sqlite.dll
extension=php_sqlite3.dll
Как установить Apache, PHP 7.3 и MySQL на CentOS 7.6
Как установить Apache, PHP 7.3 и MySQL на CentOS 7.6
В этом руководстве показано, как установить веб-сервер Apache на сервере CentOS 7 с PHP (mod_php) и базой данных MySQL. Акроним LAMP — это сокращение от Linux, Apache, MySQL, PHP.
В этом обновленном руководстве показано, как установить последние версии PHP (7.0, 7.1, 7.2 и 7.3) на CentOS 7.6.
1 Предварительное примечание
В этом руководстве я использую имя хоста server1.example.com с IP-адресом 192.168.0.100. Эти настройки могут отличаться для вас, поэтому вы должны заменить их в случае необходимости.
Я добавлю репозиторий EPEL здесь, чтобы установить последнюю версию phpMyAdmin следующим образом:
rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY* yum -y install epel-release
Чтобы редактировать файлы в оболочке, я установлю нано-редактор. Если вы предпочитаете vi для редактирования файлов, пропустите этот шаг.
yum -y install nano
2 Установка MySQL / MariaDB
MariaDB — это MySQL форк оригинального разработчика MySQL Монти Видениуса. MariaDB совместима с MySQL, и я решил использовать здесь MariaDB вместо MySQL. Запустите эту команду, чтобы установить MariaDB с yum:
yum -y install mariadb-server mariadb
Затем мы создаем ссылки запуска системы для MySQL (чтобы MySQL запускался автоматически при загрузке системы) и запускаем сервер MySQL:
systemctl start mariadb.service systemctl enable mariadb.service
Установите пароли для учетной записи root MySQL:
mysql_secure_installation [root@server1 ~]# mysql_secure_installation NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY! In order to log into MariaDB to secure it, we'll need the current password for the root user. If you've just installed MariaDB, and you haven't set the root password yet, the password will be blank, so you should just press enter here. Enter current password for root (enter for none):3 Установка Apache
CentOS 7 поставляется с Apache 2.4. Apache напрямую доступен в виде пакета CentOS 7, поэтому мы можем установить его следующим образом:
yum -y install httpdТеперь настройте систему для запуска Apache во время загрузки .
systemctl start httpd.service systemctl enable httpd.serviceЧтобы получить доступ к веб-серверу извне, нам нужно открыть порты HTTP (80) и HTTPS (443) в брандмауэре. Брандмауэр по умолчанию в CentOS - firewalld, который можно настроить с помощью команды firewalld-cmd.
firewall-cmd --permanent --zone=public --add-service=http firewall-cmd --permanent --zone=public --add-service=https firewall-cmd –reloadТеперь направьте ваш браузер на IP-адрес вашего сервера, в моем случае http://192.168.0.100, и вы должны увидеть страницу-заполнитель Apache.
4 Установка PHP
Версия PHP, которая поставляется с CentOS по умолчанию, довольно старая (PHP 5.4). Поэтому в этой главе я покажу вам некоторые варианты установки более новых версий PHP, таких как PHP 7.0 - 7.3, из репозитория Remi.
Добавьте репозиторий Remi CentOS.
rpm -Uvh http://rpms.remirepo.net/enterprise/remi-release-7.rpmУстановите yum-utils так, как нам нужна утилита yum-config-manager.
yum -y install yum-utilsи запустите yum update
yum updateТеперь вам нужно выбрать, какую версию PHP вы хотите использовать на сервере. Если вам нравится использовать PHP 5.4, перейдите к главе 4.1. Чтобы установить PHP 7.0, следуйте командам в главе 4.2, для PHP 7.1 - главе 4.3, для PHP 7.4 используйте главу 4.4, а для PHP 7.3 - вместо главы 4.5. Следуйте только одной из глав 4.x, а не всем, поскольку вы можете использовать только одну версию PHP одновременно с Apache mod_php.
4.1 Установите PHP 5.4
Чтобы установить PHP 5.4, выполните эту команду:
yum -y install php4.2 Установить PHP 7.0
Мы можем установить PHP 7.0 и модуль Apache PHP 7.0 следующим образом:
yum-config-manager --enable remi-php70 yum -y install php php-opcache4.3 Установить PHP 7.1
Если вы хотите использовать PHP 7.1 вместо этого, используйте:
yum-config-manager --enable remi-php71 yum -y install php php-opcache4.4 Установите PHP 7.2
Если вы хотите использовать PHP 7.2 вместо этого, используйте:
yum-config-manager --enable remi-php72 yum -y install php php-opcache4.5 Установите PHP 7.3
Если вы хотите использовать PHP 7.3, используйте:
yum-config-manager --enable remi-php73 yum -y install php php-opcacheВ этом примере и в загружаемой виртуальной машине я буду использовать PHP 7.3.
Мы должны перезапустить Apache, чтобы применить изменения:
systemctl restart httpd.service5 Тестирование PHP / Получение подробной информации о вашей установке PHP
Корнем документа веб-сайта по умолчанию является / var / www / html. Мы создадим небольшой файл PHP (info.php) в этом каталоге и вызовем его в браузере для проверки установки PHP. Файл отобразит много полезной информации о нашей установке PHP, например, об установленной версии PHP.
nano /var/www/html/info.phpТеперь мы вызываем этот файл в браузере (например, http://192.168.0.100/info.php): Как видите, PHP 7.3 работает и работает через обработчик Apache 2.0, как показано в строке Server API. Если вы прокрутите дальше вниз, вы увидите все модули, которые уже включены в PHP. MySQL там не указан, что означает, что у нас пока нет поддержки MySQL в PHP.
6 Получение поддержки MySQL в PHP
Чтобы получить поддержку MySQL в PHP, мы можем установить пакет php-mysqlnd. Рекомендуется установить некоторые другие модули PHP, так как они могут вам понадобиться для ваших приложений. Вы можете искать доступные модули PHP5 следующим образом:
yum search phpВыберите те, которые вам нужны, и установите их так:
yum -y install php-mysqlnd php-pdoНа следующем шаге я установлю некоторые распространенные модули PHP, необходимые для систем CMS, такие как WordPress, Joomla и Drupal:
yum -y install php-gd php-ldap php-odbc php-pear php-xml php-xmlrpc php-mbstring php-soap curl curl-develТеперь перезапустите веб-сервер Apache:
systemctl restart httpd.serviceТеперь перезагрузите http://192.168.0.100/info.php в вашем браузере и снова прокрутите вниз до раздела модулей. Теперь вы должны найти много новых модулей, таких как curl и т.д.
Если вам больше не нужен вывод информации PHP, удалите этот файл по соображениям безопасности.
rm /var/www/html/info.php7 Установка phpMyAdmin
phpMyAdmin - это веб-интерфейс, с помощью которого вы можете управлять своими базами данных MySQL.
phpMyAdmin теперь можно установить следующим образом:
yum -y install phpMyAdminТеперь мы настраиваем phpMyAdmin. Мы изменили конфигурацию Apache, чтобы phpMyAdmin разрешал соединения не только с локального хоста (закомментировав раздел и добавив строку «Требовать все предоставлено»):
nano /etc/httpd/conf.d/phpMyAdmin.conf [. ] Alias /phpMyAdmin /usr/share/phpMyAdmin Alias /phpmyadmin /usr/share/phpMyAdminAddDefaultCharset UTF-8 # Apache 2.4 # # Require ip 127.0.0.1 # Require ip ::1 # Require all granted# Apache 2.2 Order Deny,Allow Deny from All Allow from 127.0.0.1 Allow from ::1 Options none AllowOverride Limit Require all granted [. ]Перезапустите Apache, чтобы применить изменения конфигурации
systemctl restart httpd.serviceПосле этого вы можете получить доступ к phpMyAdmin по адресу http://192.168.0.100/phpmyadmin/:
PHPMyAdmin на CentOS
8 Скачать как виртуальную машину
Эта настройка доступна для загрузки виртуальной машины в формате ova / ovf (совместим с VMWare и Virtualbox) для подписчиков howtoforge.
Данные для входа в виртуальную машину
Пароль root для Linux: howtoforge.
Пароль root для MySQL: howtoforge
Пожалуйста, измените оба пароля при первом входе в систему.
IP-адрес виртуальной машины 192.168.0.100
