PHP — Installation on Linux/Unix
If you plan to install PHP on Linux or any other variant of Unix, then here is the list of prerequisites −
A working PHP-supported database, if you plan to use one ( For example MySQL, Oracle etc. )
Any other supported software to which PHP must connect (mail server, BCMath package, JDK, and so forth)
An ANSI C compiler
Gnu make utility − you can freely download it at https://www.gnu.org/software/make
Now here are the steps to install Apache and PHP5 on your Linux or Unix machine. If your PHP or Apache versions are different then please take care accordingly.
If you haven’t already done so, unzip and untar your Apache source distribution. Unless you have a reason to do otherwise, /usr/local is the standard place.
Build the apache Server as follows
Unzip and untar your PHP source distribution. Unless you have a reason to do otherwise, /usr/local is the standard place.
Configure and Build your PHP, assuming you are using MySQL database.
Install the php.ini file. Edit this file to get configuration directives −
Tell your Apache server where you want to serve files from, and what extension(s) you want to identify PHP files A .php is the standard, but you can use .html, .phtml, or whatever you want.
Go to your HTTP configuration files (/usr/local/apache/conf or whatever your path is)
Open httpd.conf with a text editor.
Search for the word DocumentRoot (which should appear twice), and change both paths to the directory you want to serve files out of (in our case, /home/httpd). We recommend a home directory rather than the default /usr/local/apache/htdocs because it is more secure, but it doesn.t have to be in a home directory. You will keep all your PHP files in this directory.
Add at least one PHP extension directive, as shown in the first line of code that follows. In the second line, we.ve also added a second handler to have all HTML files parsed as PHP.
Restart your server. Every time you change your HTTP configuration or php.ini files, you must stop and start your server again.
Set the document root directory permissions to world-executable. The actual PHP files in the directory need only be world-readable (644). If necessary, replace /home/httpd with your document root below −
Open a text editor. Type: . Save this file in your Web server’s document root as info.php.
Start any Web browser and browse the file.you must always use an HTTP request (http://www.testdomain.com/info.php or http://localhost/info.php or http://127.0.0.1/info.php) rather than a filename (/home/httpd/info.php) for the file to be parsed correctly
You should see a long table of information about your new PHP installation message Congratulations!
Источник
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.
Источник
How to Use and Execute PHP Codes in Linux Command Line – Part 1
PHP is an open source server side scripting Language which originally stood for ‘Personal Home Page‘ now stands for ‘PHP: Hypertext Preprocessor‘, which is a recursive acronym. It is a cross platform scripting language which is highly influenced by C, C++ and Java.
Run PHP Codes in Linux Command Line – Part 1
A PHP Syntax is very similar to Syntax in C, Java and Perl Programming Language with a few PHP-specific feature. PHP is used by some 260 Million websites, as of now. The current stable release is PHP Version 5.6.10.
PHP is HTML embedded script which facilitates developers to write dynamically generated pages quickly. PHP is primarily used on Server-side (and JavaScript on Client Side) to generate dynamic web pages over HTTP, however you will be surprised to know that you can execute a PHP in a Linux Terminal without the need of a web browser.
This article aims at throwing light on the command-line aspect of PHP scripting Language.
1. After PHP and Apache2 installation, we need to install PHP command Line Interpreter.
Next thing, we do is to test a php (if installed correctly or not) commonly as by creating a file infophp.php at location ‘/var/www/html‘ (Apache2 working directory in most of the distros), with the content , simply by running the below command.
and then point your browser to http://127.0.0.1/infophp.php which opens this file in web browser.
Check PHP Info
Same results can be obtained from the Linux terminal without the need of any browser. Run the PHP file located at ‘/var/www/html/infophp.php‘ in Linux Command Line as:
Check PHP info from Commandline
Since the output is too big we can pipeline the above output with ‘less‘ command to get one screen output at a time, simply as:
Check All PHP Info
Here Option ‘-f‘ parse and execute the file that follows the command.
2. We can use phpinfo() which is a very valuable debugging tool directly on the Linux command-line without the need of calling it from a file, simply as:
PHP Debugging Tool
Here the option ‘-r‘ run the PHP Code in the Linux Terminal directly without tags and > .
3. Run PHP in Interactive mode and do some mathematics. Here option ‘-a‘ is for running PHP in Interactive Mode.
Press ‘exit‘ or ‘ctrl+c‘ to close PHP interactive mode.
Enable PHP Interactive Mode
4. You can run a PHP script simply as, if it is a shell script. First Create a PHP sample script in your current working directory.
Notice we used #!/usr/bin/php in the first line of this PHP script as we use to do in shell script (/bin/bash). The first line #!/usr/bin/php tells the Linux Command-Line to parse this script file to PHP Interpreter.
Second make it executable as:
5. You will be surprised to know you can create simple functions all by yourself using the interactive shell. Here is the step-by step instruction.
Start PHP interactive mode.
Create a function and name it addition. Also declare two variables $a and $b.
Use curly braces to define rules in between them for this function.
Define Rule(s). Here the rule say to add the two variables.
All rules defined. Enclose rules by closing curly braces.
Test function and add digits 4 and 3 simply as :
Sample Output
You may run the below code to execute the function, as many times as you want with different values. Replace a and b with values of yours.
Sample Output
You may run this function till you quit interactive mode (Ctrl+z). Also you would have noticed that in the above output the data type returned is NULL. This can be fixed by asking php interactive shell to return in place of echo.
Simply replace the ‘echo‘ statement in the above function with ‘return‘
and rest of the things and principles remain same.
Here is an Example, which returns appropriate data-type in the output.
PHP Functions
Always Remember, user defined functions are not saved in history from shell session to shell session, hence once you exit the interactive shell, it is lost.
Hope you liked this session. Keep Connected for more such posts. Stay Tuned and Healthy. Provide us with your valuable feedback in the comments. Like ans share us and help us get spread.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
Портирование COM на Linux
Мне нравится технология COM. Но речь пойдет не о технологии, восхвалении или недостатках COM, а опыте переноса и реализации на Linux. Велосипед? Целесообразность? Давайте не будем на этом заострять внимание.
В общем понимании, объект класса, реализующий как минимум один COM-интерфейс. Реализация объекта в основном скрывается в динамически подключаемой библиотеке, называемой COM-сервер (2) , для использования публикуются и распространяются интерфейсы.
COM-интерфейс, абстрактный класс содержащий только чисто виртуальные функции. Выделяется особый интерфейс IUnknown, любой COM-объект обязан реализовывать данный интерфейс.
Каждый COM-интерфейс должен содержать некий свой идентификатор. В COM он определяется структурой GUID и вот тут столкнемся с первым недостатком COM. GUID непонятен и не читаем ну и все остальное описанное на Wiki. Нам он то же нужен, но в более читаемом и понятном виде (назовем его uiid).
Помимо идентификатора интерфейса, выделяется и идентификатор класса (clsuid), необходимый для создания объекта. В нашем случае, т.к. это более менее читаемый идентификатор, который может определять суть, можно пока забыть о их публикации (возможно это не хорошо).
Резюме
COM-объект, содержит единственный идентификатор класса. Реализует как минимум один COM-интерфейс — IUnknown (любой COM-интерфейс имеет уникальный идентификатор интерфейса). Разные реализации COM-объекта могут иметь один и тот же идентификатор класса (пример: release и debug версия).
Динамически подключаемой библиотека (для Linux это Shared object — so) реализующая как минимум один COM-объект. Сервер должен экспортировать определенный набор функций:
Создает объект класса по clsuid, увеличивает количество ссылок на so, каждый раз при успешном создании объекта. Вызов IUnknown::AddRef, так же должен увеличивать счетчик ссылок на so, а IUnknown::Release должен уменьшать.
Если количество ссылок на SO равно 0, то можно выгружать библиотеку.
Регистрирует в “реестре” все clsuid сервера. Вызывается единожды при инсталляции COM-сервера.
Удаляет из “реестра” записи о зарегистрированных clsuid сервера. Вызывается единожды при деинсталляции COM-сервера.
Пример SimpleHello, объявляем интерфейс IHello:
Набор макросов скрывает реализации функций, предоставляя более структурированное объявление и логику.
Dom::Implement — скрывает реализацию методов интерфейса IUnknown, добавляет “сахарок”, при объявлении интерфейсов реализуемых объектом (С++11 и variadic templates):
Интерфейс IRegistryServer — определяет набор методов работы с “реестром” COM-серверов.
Важность реестра можно недооценить, но он является наверное главным столпом COM. Microsoft пишет в системный реестр, создает сложную структуру описания интерфейсов и их атрибутов (idl), я пошел немного по другому пути.
В реализации реестр базируется на файловой системе.
Какие плюшки? Понятность, простота, возможность восстановления, особая плюшка при регистрации сервера можно задать некого рода namespace (директорию относительно базового реестра в которой будет регистрироваться объекты сервера), тем самым можно реализовать целостность и версионность приложений использующих технологию.
Из недостатков, возможные проблемы с безопасностью, подмена реализаций объектов.
Как использовать, пример приложения (4)
Для того чтобы заставить все работать потребуется еще небольшая “библиотечка” и небольшая “программка”.
“Библиотечка” — ни что иное как обертка реализующая и собирающая все в единое целое, работу с реестром, загрузку\выгрузку SO, создание объектов.
Она единственная должна быть указана при сборке приложения. Все остальное, “хочется верить”, она сделает сама.
“Программка” — regsrv — собственно это аналог программы Microsoft RegSrv32, выполняющей те же действия (+ возможность указания namespace, + возможность получения списка зарегистрированных clsuid и COM-серверов).
Dom (Dynamic Object Model), моя реализация для Linux.
Источник