Running php in linux

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.

Читайте также:  Windows server чистка реестра

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.

Источник

Apache NetBeans 12.5

Last reviewed on 2019-02-02

This tutorial shows how to configure the PHP development environment in the Ubuntu operating system (7.10 and later). This involves installing and configuring the PHP engine, a MySQL database, an Apache web server, and the XDebug debugger.

Requirements

To follow this tutorial, you need the following software and resources.

Apache HTTP Server 2.2 is recommended.

A database server

MySQL Server 5.0 is recommended.

A PHP debugger (optional)

XDebug 2.0 or later

Typically, development and debugging is performed on a local web server, while the production environment is located on a remote web server. Setting up a remote web server is described in + Deploying a PHP Application on a Remote Web Server Using the NetBeans IDE+. This tutorial has you set up a local web server. PHP support can be added to a number of local web servers (IIS, Xitami, and so on), but most commonly Apache HTTP Server is used.

Installing the Software

This tutorial shows how to configure the PHP development environment in Ubuntu 7.04 and later. You need to:

Install the Apache2 HTTP server, the PHP5 engine, the MySQL 5.0 database server, and the PHP5-MySQL module. These packages can be installed together as the LAMP stack, or they can be installed separately.

See the Ubuntu community for more information on installing Apache, MySQL, and PHP.

Installing the Software Packages Together

Ubuntu provides a Linux AMP (LAMP) package that contains all the necessary packages for your PHP environment. You can install the software by executing the following command at the command prompt in the Terminal window:

The lamp-server package includes the most suitable version of PHP, Apache 2, MySQL, and PHP5-MySQL.

Installing the Software Packages Separately

Instead of installing the entire set of LAMP packages, you can also install the packages individually. This is useful if you already have installed one of the components, such as the Apache server or MySQL database server. You can use command-line tools or the Synaptic Package Manager GUI.

The individual packages to install are the following:

Checking the Installation

After you set up your PHP web stack, check that it is installed correctly and that your Apache server recognizes your PHP engine.

To check that Apache and PHP are installed and running, open NetBeans IDE and create a PHP project. In the index.php file, enter the PHP method phpinfo() . Run the file. The standard PHP information page should display.

Troubleshooting

The following are some frequently encountered problems when checking the installation of your PHP stack in Ubuntu:

The browser window displays a Not Found error for

USER/PROJECT/index.php . Remove the

USER string from the URL. For example, if this error appears for the URL

ubuntu/test1/index.php , change the URL to test1/index.php . Note that you can set the URL for a PHP project in NetBeans IDE either when you create the project, or by right-clicking the project node and going to Properties > Run Configuration.

The browser shows you a popup asking you to open the file, as if the PHP engine is not recognized. There’s a problem with your php5-common package. Replace it with php5 and phpmyadmin . To replace php5-common , run the following two commands:

Specifying the Document Root for the Apache2 HTTP Server

The Document Root is the directory where the Apache HTTP server takes files for displaying in the browser. The Document Root is specified in the file that defines your virtual host. The default virtual host configuration file is

with the document root

We recommend that you create your own virtual host and enable it instead of editing the default one.

Creating the Document Root Location

Choose Places > Home Folder.

From the context menu, choose Create Folder.

Enter the name of the folder, for example, public_html.

Creating a New Virtual Host

To launch the Terminal, choose Applications > Accessories > Terminal. The Terminal window opens.

To copy the configuration file of the default virtual host to a new file ( mysite ), type the following command at the command prompt:

Run the gedit application and edit the new configuration file ( mysite ) in it:

If asked, enter the password that you specified for the root user during the installation of your operating system.

Change the Document Root to point to the new location:

Источник

Установка и базовая настройка nginx и php-fpm для разработки проектов локально в Ubuntu 16.04

Здравствуй, уважаемый пользователь Хабрахабра. Мое повествование будет о том, как подготовить почву для локальной веб-разработки проектов в операционной системе Ubuntu 16.04.1 LTS.

В данной статье хочется развеять и разъяснить возможные трудности связанные с установкой и настройкой ПО, которое требуется для современной веб-разработки, с которыми возможно сталкиваются начинающие разработчики и не только.

Технологии которые будут использованы в статье: nginx, php-fpm.

Перед началом повествования, хочу отметить, что я проделывал все эти действия на «голой» системе.
Я буду работать с пакетным менеджером aptitude. Так же рекомендую обновить индекс пакетов и сами пакеты перед установкой ПО. В статье мы проделаем эти действия вместе.

Установка пакетного менеджера aptitude, обновление индекса и пакетов

Обновляем пакеты (команда обновит все пакеты, для которых есть новые версии, если потребуется удаление пакетов, то оно будет выполнено).

Установка и настройка nginx (версия >= 1.10.0)

Проверяем версию, чтобы убедиться что не установили старую, то есть ниже 1.10.0.

Установку и запуск произвели, теперь пойдем в каталог туда куда установлен наш nginx и посмотрим на его структуру. Каталог nginx находится по такому пути:

Посмотреть содержимое директории можно командой ls, с флагами -la будет удобнее просматривать содержимое каталога (в действительности эту команду с конкретными флагами можно описать детальнее и вернее, но у нас сегодня другая тема).

Наc интересуют в данный момент два каталога, которые вы видите на скриншоте. Это каталоги sites-available и sites-enabled.

Давайте перейдем в каталог sites-available и начнем конфигурировать наш виртуальный хост (сайт).

Перед началом создания конфигурационного файла, проверим что лежит у нас в данном каталоге. В моей случае каталог не пустой, в нем уже есть конфигурационные файлы, я их затер, чтобы не вводить вас в заблуждение.

В случае установки nginx «с нуля», именно «с нуля», так как при удалении nginx командой
или конфигурационные файлы остаются и если вы вдруг будете не понимать, почему nginx не работает и захотите его переустановить (обычно к такому прибегают начинающие пользователи Linux), то и после переустановки он не будет корректно работать, из-за того что в старых конфигурационных файлах (они не удаляются после удаления командой remove) прописаны неверные настройки, их придется удалить, либо настроить верно, только тогда nginx заработает.

Рекомендую удалять командой sudo apt-get purge nginx или sudo apt purge nginx . Если вы используете пакетный менеджер aptitude, то команда sudo aptitude purge nginx удаляет пакет полностью со всеми зависимостями и конфигурационными файлами.

В этом каталоге будет по умолчанию один файл, с названием default. В нем будет конфигурационный файл с примером, с комментариями, его вы можете изучить на досуге, а можете и вовсе удалить (всегда можно обратиться к официальной документации).

Создадим свой конфигурационный файл, который будет соответствовать названию домена нашего локального сайта (или реального, если уже знаете его название). Это удобно, в будущем, когда будет много конфигурационных файлов, то это избавит вас от путаницы в них. У меня этот файл будет называться project.local.

Посмотрим что получилось.

Теперь откроем его в редакторе, я открою его в nano.

Видим что он у нас пустой. Теперь перейдем к формированию нашего файла. Нужно привести конфигурацию к такому виду, как написано ниже. Я опишу только жизненно важные директивы этого файла, описывать остальное не буду, так как это не является на данный момент важным, все-таки у нас тема базовой настройки. Этих настроек с «горкой» хватит для разработки проектов локально, не только мелких, но и довольно крупных. В следующих статьях опишу отдельно каждые использованные директивы (именно так называются строки, например server_name) этого файла.

Смотрите комментарии прям в конфигурационном файле.

Сохраняем файл. Теперь нам надо проверить, нет ли в нем ошибок. Сделать мы это можем командой.

Если видим такую информацию как на скриншоте, значит у нас все верно, может продолжать настройку. Если вы получаете какие-либо ошибки, стоит перепроверить конфигурационный файл.

Теперь нам надо активировать конфигурационный файл, в каталоге /etc/nginx/sites-enabled/ необходимо создать симлинк (символическая ссылка). Если у вас nginx был установлен «с нуля», то в этом каталоге есть симлинк на файл default, про который рассказывалось выше, его можно удалить, если он вам не требуется. Переходим в нужный каталог.

Теперь мы в нужном каталоге. Давайте создадим наш симлинк. Для создания используется команда ln с флагом -s, далее мы укажем путь до нашего конфига project.local.

Посмотрим на наш созданный симлинк.

Чтобы убедиться что мы делаем еще все верно опять запустим команду.

Если все ок, едем дальше.

Файл hosts

Этот файл находится по пути /etc/hosts. Наличие в нем записей, позволяет запускать nginx с использованием в качестве домена localhost. В этом файле можно присваивать альтернативные псевдонимы, например для нашего проекта project.local, мы присвоим домен project.local.

Открываем файл в редакторе nano.

У вас в этом файле будет и другая информация, просто игнорируйте ее. Вам всего лишь нужно добавить строку как на моем скриншоте.

Не забываем сохранить файл. На этом настройка файла hosts закончена.

Установка php-fpm (>=7.0)

Проверяем установленную версию, на всякий случай, хотя в Ubuntu 16.04.1 в репозиториях лежит именно 7.0 версия.

Убеждаемся что все ок. Стартуем php-fpm.

Если будете править конфиги, то не забывайте рестартовать демон. Это делает так. Но нам это не потребуется.

На этом установка и настройка php-fpm закончена. Правда, это все. Это не магия, путь до сокета php-fpm у нас уже был прописан в конфигурационном файле. Конечно, вам могут понадобиться какие-либо расширения php для разработки личных проектов, но их вы можете поставить по мере того как они будут требоваться.

Теперь пойдем для в каталог с нашим проектом, у меня он лежит по такому пути.

Поднимемся на каталог выше и сделаем права 777 (то есть мы будем делать полные права каталогу с нашим проектом project.local). В будущем это избавим нас от лишних проблем.

На этом настройка ПО завершена, давайте создадим тестовый файл в нашем рабочем каталоге project.local и убедимся что все работает. Я создам файл index.php с таким содержанием.

Идем в браузер и видим что у нас все прекрасно работает! Интерпретатор php в том числе.

Источник

Читайте также:  Anaconda navigator linux mint
Оцените статью
Software or Resource Version Required