- How to Use and Execute PHP Codes in Linux Command Line – Part 1
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Настройка PHP в Linux
- Введение
- Установка PHP
- Настройка PHP
- Проверка
- Using php in linux
- Using APT
- Better control of configuration
- Common Problems
- User Contributed Notes 6 notes
- Installation on Unix systems
- Table of Contents
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.
Источник
Настройка PHP в Linux
Четверг, 10 Октябрь 2013 00:00
Устанавливаем и настраиваем PHP под Linux. Интерпретатор PHP — это программа, выполняющая команда языка PHP. Язык PHP является широко используемым скриптовым языком общего назначения, который особенно подходит для веб-разработки и может быть встроен в HTML.
Введение
Данная статья написана для версии PHP 5.4.26, но также походит для других версий PHP. От версии дистрибутива Linux ничего не зависит, в экспериментах были опробованы CentOS 6.5, CentOS 7.0, Fedora 17, Fedora 20.
Установка PHP
1.Запустим yum со следующими параметрами:
Настройка PHP
1. Увеличение объема памяти PHP-скрипта
В файле /etc/php.ini заменим значение memory_limit = 16M на memory_limit = 128M
2. Увеличение максимального времени выполнения PHP-скрипта
В файле /etc/php.ini заменим значение max_execution_time = 30 на max_execution_time = 120
3. Увеличение размера максимальной загрузки PHP-скрипта
В файле /etc/php.ini заменим значение max_upload_size = 2M на max_upload_size = 50M
В файле /etc/php.ini заменим значение post_max_size = 8M на post_max_size = 50M
4. Разрешаем использовать короткие теги
В файле /etc/php.ini проверяем значение short_open_tag = On .
5. Создание папки /usr/share/phpinfo
6. Создание файла /usr/share/phpinfo/index.php со следующим содержанием:
7. Изменение прав доступа к файлу index.php
8. Создание файла /etc/httpd/conf.d/phpinfo.conf со следующим содержанием:
#phpinfo – функция PHP для текущей конфигурации
# По умолчанию разрешен только локальный хост
9. Перезапуск сервера Apache
Или для CentOS/RHEL 7.0 и Fedora 20:
Проверка
Проверка из командной строки:
В результате прямо в консоли появится информация о версии интерпретатора.
[root]# php -v
PHP 5.4.26 (cli) (built: Mar 7 2014 10:09:20)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies
Источник
Using php in linux
This section contains notes and hints specific to installing PHP on » Debian GNU/Linux.
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 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
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
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 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
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
Источник
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.
Источник