Php – Install Php In Linux and Create Development Environment
As stated previous post Php is portable language. Which makes Php supports a lot of different platforms. In this post we will look how to install Php and IDE named Eclipse in Linux operating system like Fedora and Ubuntu. During post we will give both Fedora or yum and Ubuntu apt instructions. Let’s start the installation process.
Fedora, CentOS, RedHat Installation
In this part we assume we have all ready installed Fedora. We will install Php or Php interpreter and Eclipse.
Install Php
We will install Php with the command line package management tool named yum . We will issue following command in order to install Php interpreter and core libraries.
Install Php
Install Eclipse
Next step is installing Eclipse we will install Eclipse Php .
Install Eclipse
Ubuntu, Debian, Mint Installation
Install Php
We will install Php on ubuntu with the following command.
Install Eclipse
We will install Eclipse on Ubuntu from following url and unzip files.
Alternative IDE Nano or Text Editor
Another way to write Php code is using simple operating system provided text editor or third party editor. We will use nano as terminal based editor in this example.
Ubuntu, Debian, Mint
Fedora, CentOS, RedHat
Now create file named index.php with the following command.
and add following lines to the file.
Simply run Php interpreter by providing the code file named like below. We will run php against index.php
2 thoughts on “Php – Install Php In Linux and Create Development Environment”
Woah! I’m really loving the template/theme of this site. It’s simple, yet effective. A lot of times it’s very difficult to get that “perfect balance” between usability and appearance. I must say you have done a excellent job with this. Additionally, the blog loads super quick for me on Internet explorer. Superb Blog!
Источник
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:
Источник
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 на ubuntu
Зачем? Это самый первый вопрос, который задаст большинство. Отвечу: 1) Дефолтный php без зачастую нужных вещей вроде pcntl, и к тому же с вкомпиленным генератором неведомой совокупительной фигни Suhosin Patch. 2) Сборка модулей, которых нет в репозитории. 3) Нет руководств такого типа. Нет, действительно нету, лишь короткие руководства, которые с оговоркой можно назвать логом ./configure && make && make install, и по которым сложно что-то собрать из-за наличия требований дополнительных библиотек. 4) Я не буду писать про фан. Просто не буду, т.к. мы не балуемся, а собираем продукт для работы. Многие найдут это плюсом, но не я. 5) Внезапно возник вопрос сборки своего модуля. Навыки сборки под никс очень помогли в сборке под винду, где и был написан экстеншн. Можно конечно было сразу писать под никсами… Но ставить и настраиватькастомизировать никсы только ради одного проекта(в консоли на удаленном сервере разрабатывать как-то не особо приятно) мне не хотелось.
Начинаем установку Создаем каталог и переходим в него:
На девственной ubuntu-server apt-get потребует скачать около 85мб. Устанавливать мы будем в /opt, чтобы не путать с файлами дистрибутива.
Приступим к сборке апача Комментировать ничего не буду, т.к. тут все прозрачно и в комментариях не нуждается.
Устанавливаем PHP Да, именно его модули требуют кучу зависимостей. Я конфигурировал для MySQL/SQLite СУБД, для других собирайте сами. Не нужно бояться добавить сюда лишнего — на производительность это не повлияет.
Пара слов о опциях. PHP-разработчик обязан знать, что значат эти модули(опция начиная с —with-curl), а тот, кто не разработчик, но кому волею судьбы пришлось настраивать сервер, пусть просто поверит, что они более-менее оптимальны и ничего необходимого типа pdo или mysqli не вырезано, как иногда бывает. Это же касается и конфига php.ini.
Правим конфиг апача
Я заменяю значение DocumentRoot на «/var/www», добавляю в DirectoryIndex index.php, добавляю AddType application/x-httpd-php .php Создаем phpinfo.php с содержимым и наслаждаемся видом ненастроенного php(запускаем апач через /opt/apache2/bin/apachectl start).
Правим эти параметры(я даже не буду заикаться насчет того, что они значат): error_reporting = E_ALL display_errors включаем для дебага, на боевой раскладке же выключаем. log_errors = On post_max_size = 64M(для типичных задач это более чем) magic_quotes_gpc = Off(и почему они по молчанию включены? Ума не приложу) include_path = «.:/opt/php5.2/lib/php»(сюда я положил ZF и прочие интересные вещи) upload_max_filesize = 64M(равен post_max_size) Подскажу, что в виме поиском занимается «?»
Автоматический запуск Для начала уберем дефолтный апач из запуска, нам поможет удобная утилитка rcconf(ее использовать нагляднее, чем update-rc.d, привык ее юзать):
Теперь в rc.local добавляем строку запуска нашего апача, что позволит запускаться ему при старте:
Строка запуска выглядит так: /opt/apache2/bin/apachectl start Можно же все сделать и правильно, через добавление скрипта, но я ограничусь этим.
Устанавливаем XCache Сборку комментировать не буду:
Комментируем zend_extension_ts, выставляем xcache.admin.user в имя админа, xcache.admin.pass в md5 пароля, xcache.size в 64M, xcache.optimizer в On, путь zend_extension выставляем в «/opt/php5.2/lib/php/extensions/no-debug-non-zts-20060613/xcache.so». Если путь выставлен правильно, то в phpinfo() мы увидим параметры xcache, а статистику сможем посмотреть в админке. Если этого нету, то смотрим логи апача и ищем ошибку.
Добавляем в php.ini extension=memcache.so, путь прописывать не надо, она лежит по дефолтному. Ставить из pear на никсах легко, это вам не windows =)
nginx Меняем порт у апача, вводим в гугле nginx reverse proxy, читаем, делаем. Много раз переписывать одно и то же нет не только желания, но и смысла. Автозагрузка аналогичная апачу. Update: Использование Nginx Как Reverse-Proxy Сервера На Загруженных Сайтах, nginx как reverse proxy
В следующих сериях 1. Хоррор «Сборка минимального PHP под Windows при помощи VS 2008». Сборка экстеншенов: helloworld. Если хватит кармы, то будет завтра-послезавтра, т.к. уже написана. 2. Сборка экстеншенов на linux. Реализация TEA.