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!
Источник
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.
Software or Resource
Version Required
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:
Источник
Apache NetBeans 12.5
This tutorial needs a review. You can open a JIRA issue, or edit it in GitHub following these contribution guidelines.
В данном учебном курсе рассматривается процедура настройки среды разработки PHP в операционной системе Ubuntu (версия 7.10 и более поздние). Эта процедура предполагает установку и настройку механизма PHP, базы данных MySQL, веб-сервера Apache и отладчика XDebug.
Для работы с этим учебным курсом требуется следующее программное обеспечение и ресурсы.
Программное обеспечение или материал
Требуемая версия
Пакет загрузки PHP
Рекомендуется использовать HTTP-сервер Apache 2.2.
Сервер базы данных
Рекомендуется использовать сервер MySQL 5.0.
Отладчик PHP (не обязательно)
Версия XDebug 2.0 или более поздняя
Как правило, разработка и отладка выполняются на локальном веб-сервере, в то время как производственная среда размещена на удаленном веб-сервере. Настройка удаленного веб-сервера описана в разделе + Развертывание приложения PHP на удаленном веб-сервере с помощью IDE NetBeans+. Этот учебный курс содержит информацию, необходимую для настройки локального веб-сервера. Поддержка PHP может добавляться к целому ряду локальных веб-серверов (IIS, Xitami и т.д.), но обычно используется сервер HTTP Apache.
Установка программного обеспечения
В данном учебном курсе рассматривается процедура настройки среды разработки PHP в операционной системе Ubuntu (версия 7.04 и более поздние). Необходимо выполнить следующие действия:
Установить сервер Apache2 HTTP, механизм PHP5, сервер базы данных MySQL 5.0 и модуль PHP5-MySQL. Эти пакеты можно установить одновременно как стек LAMP или установить по отдельности.
Для получения дополнительных сведений об установке Apache, MySQL и PHP см. Сообщество Ubuntu.
Одновременная установка всех пакетов программного обеспечения
Ubuntu предоставляет пакет Linux AMP (LAMP), который содержит все необходимые пакеты для среды PHP. Для установки программного обеспечения можно выполнить следующую команду в командной строке в окне терминала:
Пакет lamp-server включает в себя наиболее удобную версию PHP, Apache 2, MySQL и PHP5-MySQL.
Установка пакетов программного обеспечения по отдельности
Вместо установки целого набора коллекций LAMP пакеты можно также установить индивидуально. Эта функция используется, если один из компонентов (например, сервер Apache или сервер базы данных MySQL) уже установлен. Можно использовать средства командной строки или графический пользовательский интерфейс Synaptic Package Manager.
Отдельно могут быть установлены следующие пакеты:
Проверка установки
После настройки пакета PHP Web Stack убедитесь в том, что он установлен правильно, а сервер Apache распознает механизм PHP.
Чтобы убедиться, что Apache и PHP установлены и запущены, откройте IDE NetBeans и создайте проект PHP. В файле index.php введите метод PHP phpinfo() . Запустите файл. При этом должна отобразиться стандартная информационная страница PHP.
Устранение проблем
Ниже перечислены часто возникающие проблемы при проверке установки стека PHP в Ubuntu:
*В окне браузера отображается ошибка «Not Found» для
USER/PROJECT/index.php *. Удалите строку
USER из URL-адреса. Например, если эта ошибка происходит для URL-адреса
ubuntu/test1/index.php , измените его на test1/index.php . Обратите внимание, что можно настроить адрес URL для проекта PHP в IDE NetBeans либо при создании проекта или путем щелчка правой кнопки мыши узла проекта и перехода в ‘Свойства’ > ‘Запустить конфигурацию’.
В браузере отображается всплывающее окно с запросом на открытие файла, как если бы механизм PHP не распознавался. Пакет php5-common содержит ошибку. Замените его пакетами php5 и phpmyadmin . Для замены пакета php5-common необходимо выполнить следующие две команды:
Указание корневого узла документа для сервера HTTP Apache2
Корневой узел документов представляет собой папку, из которой сервер HTTP Apache извлекает файлы для отображения в браузере. Корневой узел документов указан в файле, определяющем виртуальный узел. Файл настройки, определяющий виртуальный узел по умолчанию:
с корневым узлом документов
Вместо изменения узла по умолчанию рекомендуется создать и активировать собственный виртуальный узел.
Создание местоположения корневого узла документов
Выберите «Places > Home Folder».
В контекстном меню выберите «Create Folder».
Введите имя папки, например public_html.
Создание нового виртуального узла
Для запуска терминала выберите «Applications>Accessories>Terminal». Откроется окно терминала.
Для копирования файла настройки из виртуального узла по умолчанию в новый файл ( mysite ) введите в командной строке следующую команду:
Запустите приложение gedit и отредактируйте в нем новый файл настройки ( mysite ):
При появлении запроса введите пароль, определенный для пользователя root во время установки операционной системы.
Измените корневой узел документов, указав в нем новое местоположение:
Источник
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.