Posts

Installing PHP

Listings of this chapter can be found in the buildin subdirectory.

The current chapter will discuss the installation procedure for PHP on Windows, Mac OS X and Linux (Ubuntu distribution).

The presence of a PHP interpreter will allow you to run PHP programs, however, a Web server will also be required to launch Web applications.

In earlier versions of PHP, an industrial Web server was used for these purposes:

  • Apache or
  • nginx.

Starting with version 5.4, the PHP distribution kit is supplied with an embedded server, the capabilities of which are quite enough for local development and testing of Web applications.

Installation in Windows

To download the Windows distribution you should visit the download section of the binary files of the official PHP site: http://windows.php.net/downloaad.

Each release is supplied with four options:

  • х86 Non Thread Sаfe – 32-bit CGI-variant of the distribution kit;
  • х86 Thread Safe – 32-bit version for installation as a Web server module;
  • x64 Non Thread Safe – 64-bit GGI-version of the distribution kit;
  • x64 Thread Safe – 64-bit version for installation as a Web server module.

The Thread Safe option is designed to safely run PHP in parallel threads within a single system process, for example, if PHP is installed as an Apache Web Server module.

Since we are going to use the built-in server, it doesn’t matter which distribution kit is chosen, it’s best to use the Non Thread Safe option. The latter option is also used when connecting PHP as an external Fast-GGI application that runs on each external request.

Before the distribution name can be placed one of the abbreviations VC11, VC14, meaning the version of Visual Studio (2012 and 2015, respectively), with which the distribution was compiled. In order to successfully launch a project, you must download the appropriate Visual C++ Redistributable Package for Visual Studio, which contains the necessary dynamic libraries:

VC 11 option

http://www.microsoft.com/en-us/download/details.aspx?id=30679;

VC 14 option

http://www.microsoft.com/en-us/download/details.aspx?id=48145.
ATTENTION! The libraries are required from the English version of Visual Studio, the Russian version of the package will not work.

After downloading the zip file, it should be unpacked into some folder, for example C:\php. You can make sure that .PHP is available by running the command line, and then go to the C:\php folder with the command1

> cd C:\php

By running the command php with the -v option on the command line, you can find out the current version of PHP:

> php -v
РНР 7.0.0 (cli) (built: Dec 3 2015 09:31:54) ( NTS)
Copyright (с) 1997-2015 The РНР Group
Zend Engine vЗ.0.0, Copyright (с) 1998-2015 Zend Technologies 

In order for the PHP command to be available at any point in the file system, the path to the PHP interpreter should be specified in the PATH environment variable. To access environment variables, open the Control Panel, go to the System section.

The fastest way to get to this point is to right-click on the Start button and select the System item from the context menu. On operating systems prior to Windows 8, select the Computer item in the Start menu and select Properties in the context menu.

In the Control Panel window that opens, with the active System section on the left, click the Advanced system settings link. Then in the System Properties window on the Advanced tab, you must click the Environment Variables button.

In the dialog box that opens, in the System variables section, find the PATH environment variable and add it to the C:\php directory. Separate paths in the value of the PATH variable are separated by a semicolon (no semicolon is required at the end of the entire line). After that the php command will be available in any folder of the computer.


1 In boldface we will highlight the commands or text entered by the user.

Installation in Mac OS X

Before installing PHP, you must install the Command Line Tools for Xcode from the AppStore.

Xcode is an integrated development environment for Mac OS X and iOS. A full Xcode download is optional, just install the command line tools and the compiler. You can verify that Xcode is installed using the command:

$ xcode-select -р
/Applications/Xcode.app/Contents/Developer

If you are prompted to install the Command Line Tools instead of the path specified above, you should install this package by running the command:

$ xcode-select –install

Now you can begin to install PHP, for which it is best to use the Homebrew package manager. At the time of this writing, Homebrew could be installed using the command:

$ ruby -e “$(curl -fsSL https://raw.githubusercontent.cam/Homebrew/install/master/install)”

However, the exact command can always be found on the official website http://brew.sh. After installation, the brew command will be available on the command line, with which you can download, remove, and update software packages.

Immediately after installation, it will not be superfluous to install additional libraries that may be required by PHP extensions:

$ brew install freetype jpeg libpng gd zlib

In order to access repositories with PHP distributions, you need to run a series of commands:

$ brew tap homebrew/dupes
$ brew tap homebrew/versions
$ brew tap homebrew/homebrew-php

By default, the brew tap command assumes that the GitHub repository names are transferred to it. Thus, the previous commands register access to the following repositories:

https://github.com/Homebrew/homebrew-dupeshttps://github.com/Homebrew/homebrew-versionshttps://github.com/Homebrew/homebrew-php

You can independently find a distribution kit or alternative project on GitHub and add it to the Homebrew package manager. If the package is no longer needed, it can be removed with the brew untap command. Of course, if possible, use the official Homebrew packages.

После выполнения приведенных выше команд надо убедиться в том, что пакеты успешно добавлены. Для этого следует выполнить команду brew tap без параметров. В результате будет выведен список добавленных репозиториев.

$ brew tap
homebrew/dupeshomebrew/php
homebrew/versions

Now you can install PHP by running the install command:

$ brew install php71

After installing PHP is ready to work.

$ php -v
РНР 7.1.2 (cli) (built: Feb 17 2017 10:51:21) ( NТS )
Copyright (с) 1997-2017 The РНР Group
Zend Engine vЗ.1.0, Copyright (с) 1998-2017 Zend Technologies

If PHP is not available, you should make sure that the path to the Homebrew sbin directory is registered in the PATH environment variable in the file ~/.bash_profile:

# Homebrew sbin path
PATH=/usr/local/sbin:$PATH

Installing on Linux (Ubuntu)

In order to install PHP in Ubuntu, you should use the apt-get package manager. You must first update the information about the repositories and current packages using the commands:

$ sudo apt-get update
$ sudo apt-get upgrade

You can then proceed with the installation:

$ sudo apt-get install php7.0

After successful installation, the php command should be available anywhere on the computer:

$ php -v
РНР 7.0.15-0uЬuntu0.16.04.4 (cli) ( NТS )
Copyright (с) 1997-2017 The РНР Group
Zend Engine vЗ.0.0, Copyright (с) 1998-2017 Zend Technologies
with Zend OPcache v7.0.15-0uЬuntu0.16.04.4, Copyright (с) 1999-2017,
bу Zend Technologies

Built-in server

To test the PHP interpreter, we create an index.php script that displays the traditional “Hello, world!” Phrase for programming books. (listing 2.1).

Listing 2.1. Hello World verification script. File index.php

<?php
echo 'Hello, world! ';
?> 

If the current user does not have administrator rights, then in the folder with the script index.php you should run the command:

php -s localhost:4000

The command will launch a Web server on the 4000 port. By contacting the browser at http:/localhost:4000/, you can see the phrase “Hello, world!”. If you are working under a system administrator account (Windows) or using the sudo command (Mac OS X or Linux), you can run the embedded server on the standard 80 port:

php -s localhost:80

In this case, the port in the address can be omitted, the browser will automatically access the 80-port assigned to the HTTP protocol: http://localhost/. By default, the current folder acts as the root directory and the index.php index file will be searched in this folder. However, using the -t option you can specify an arbitrary folder:

php -s localhost:4000 -t buildin

Log records or, as they say, server logs are output directly to the console in which it was launched. You can stop the server by pressing the key combination <Ctrl>+<C>.

hosts file

In the previous section, localhost was used as the domain, which is a pseudonym for the IP address 127.0.0.1. On the local host, the alias for the IP address is specified in the hosts file, which in a UNIX-like operating system can be found in /etc/hosts, and in Windows in C:\Windows\system32\drivers\etc\hosts.

Как правило, в файле присутствуют как минимум две записи, сопоставляющие домену localhost локальный IР-адрес 127.0.0.1 в 1Pv4- и 1Рv6-форматах:

127.0.0.1 localhost
::1 localhost

It is the presence of these records allowed us to launch the built-in server using localhost as the domain. In order to configure alternative aliases, you can add additional entries:

127.0.0.1 site.dev
127.0.0.1 www.site.dev
127.0.0.2 project.dev
127.0.0.2 www.project.dev

IP addresses starting with 127 are intended for local use, so you can assign any address from this range to test your own projects.

After adding new aliases to the hosts file, they can be used in conjunction with the built-in server, for example http://site.dev:4000/.

Broadcast outside

When using local IP addresses from the 127.X.X.X range, you can be sure that no one from the outside can access the server. If, on the contrary, you want to demonstrate the result of your application, you can specify the IP address as 0.0.0.0 as the host:

php -s 0.0.0.0:4000

In this case, you can access the Web server by accessing the IP address of the host where the server is running, for example http://192.168.0.1:4000. In order to be able to contact the host by a pseudonym, you either have to register it in the hosts file of each computer from which you are accessing the server, or register a domain name and associate it with the IP address of the computer where the server is running. Of course, in this case, when running, you will need to specify this domain name as a host.

php -S example.com:80

However, the built-in server is intended only for development, to ensure the operation of a full-fledged site, it is better to use industrial servers, such as Apache or nginx.

PHP setup

PHP has a huge variety of settings that are concentrated in the file php.ini. Immediately after installation, instead of the php.ini file, you can find only two files:

  • php.ini-production – the recommended set of parameters for the production server;
  • php.ini-development – the recommended set of parameters for a developer’s workstation.

For local development, the php.ini-development file should be renamed to php.ini. By default, the PHP interpreter sequentially searches for the configuration file in the following places:

  • along the path specified in the PHPRC environment variable;
  • in the current directory (if the script is executed under the control of the Web server);
  • in the C:\Windows\directory in the case of Windows, in the /etc/ or /etc/php7/ directory in Linux, in the /usr/local/etc/php7.0 directory on Mac OS X or in the compilation directory for any other operating system .

If there are several php.ini files and you are not sure which of them is currently being used, you can find out the path to the used php.ini file from the report of the phpinfo() information function (Listing 2.2).

Listing 2.2. Information about PHP. phpinfo.php file:

<?php
phpinfo();
?>

The function displays detailed information about all the parameters of PHP. The path to the php.ini file, which is currently used by PHP, is specified in the Loaded Configuration File parameter.

You can explicitly tell the PHP location of the php.ini file with the -c option. For Windows, the command might look like this:

php -s 127.0.0.1:4000 -c C:\php\php.ini

For a UNIX-like operating system:

php -s 127.0.0.1:4000 -с /etc/php .ini

The PHP configuration file is a plain text file that can be opened using any editor. The content of the php.ini file consists of sections and directives. Sections are enclosed in square brackets, for example [PHP], followed by directives that have the following format:

directive = value

Here directive is the name of the directive, and value is its value. All lines with a semicolon (;) at the beginning are considered comments and are ignored.

It is allowed not to specify the value value. In this case, the directive is initialized with an empty string. The same result can be achieved by setting it to none.

Immediately after installing PHP, you should edit at least one directive – the current time zone. In order to set any time zone, you need to find the date.timezone directive and bring it to the form:

date.timezone = ‘Europe/Moscow’

If the embedded server is still running, you will need to restart it in order for the changes in php.ini to take effect.

Extensions

The PHP interpreter is built on a modular basis. The language consists of a kernel to which extensions can be connected if necessary — libraries that supplement the language with new features.

For example, for image processing you can connect the GDLib extension, for connection with databases – the PDO extension, for support of multibyte strings (UTF-8) – mbstring. Some extensions have become so widespread in popularity that they were included in the kernel. For example, these are string functions from the calendar extension or support for sessions from the session extension.

Attention! The material of the current section can be skipped at first reading.

Each extension increases the amount of RAM that the PHP interpreter occupies. The more memory the interpreter consumes, the fewer PHP processes you can run on the server, the fewer connections the server can serve in one second. Therefore, extensions are connected and disconnected as needed. In order to reduce the size of the PHP executable file and, consequently, the amount of RAM consumed, most extensions are not included in the PHP core. Instead, they are compiled as external dynamic libraries: *.dll for Windows and *.so for UNIX-like operating systems.

The easiest way to find out if an extension is connected is to run the php -m command, which lists the extensions available. You can also use the phpinfo() function report (see listing 2.2). In the Configuration section, the attached extensions are indicated, and the tables that accompany each of the extensions provide a list of the parameters for this extension. Most of these parameters can be adjusted in the php.ini configuration file.

In distributions for the Windows operating system, extensions designed in the form of dynamic libraries are compiled but not connected. You can find them in the ext subdirectory of the main folder of the PHP distribution:

php_bz2.dll
php_corn_dotnet.dll
php_curl.dll


php_tidy.dll
php_xrnlrpc.dll
php_xsl.dll

In order to connect one of these external extensions, you need to edit the configuration file php.ini. The path to it can be found in the report function phpinfo(). In the php.ini configuration file, find the extension_dir directive and specify the path to the folder with extensions in it:

extension dir = “ext”

After the path to the folder with the extension is specified, you can activate the extensions themselves by using the extension directive. In the configuration file php.ini, as a rule, commented directives for all extensions from the ext folder have already been added. The necessary extension must be activated by removing the semicolon from the beginning of the line:

extension=php_mbstring.dll

В случае UNIX-подобных операционных систем установка расширений осуществляется еще проще. Как правило, они оформлены в виде отдельных пакетов. Так в Mac OS X, в основном, используется менеджер пакетов Homebrew. В разделе 2.2 PHP устанавливался при помощи команды:

$ brew install php71

In the same way, an extension is installed, only the name of the php71 package is supplemented with the name of the extension, for example, for CURL, the command might look like this:

$ brew install php71-curl

In modern Linux distributions, the installation of extensions is also done using the package manager, in the case of Ubuntu it is apt-get. Recall that installing PHP is done by the command:

$ sudo apt-get install php7.0

Extensions are installed the same way. So, CURL can be set using the command:

$ sudo apt-get install php7.0-curl

Documentation

The main source of information about PHP for all developers is the official website http://php.net. On its pages you can find the section of the documentation, including in Russian.

Unfortunately, translation into many languages is not always complete and lags behind the English version. We will not be able to highlight on these pages all the possibilities of the language, we simply will not have enough time and space for this, so you will have to refer to the PHP documentation in order to use all the PHP capabilities.

Tasks

1. Using php -h print the help information about the PHP interpreter parameters. Find a way to start interactive mode and execute the phrase “Hello world” in it.

2. Find the Sublime Text editor on the network and install it in your operating system. Create a Hello World project in it with the program from listing 2.1.

3. On the http://php.net site, use the search, find information about the construction of echo and the function phpinfo().

4. Install VirtualBox and run an alternative operating system in it: Ubuntu, if you are running Windows or Mac OS X, or Windows, if your working system is Ubuntu.

5. Install the nginx Web server and run php-fpm, configure them to work together so that they support the processing of PHP scripts.

/ October, 15 at 19:10

I create web projects, develop, optimize and promote websites. If you have any ideas or want to suggest something, then write to me and my team.

Top ↑

Leave a Reply