Php in console linux
Указание конкретного файла для запуска.
Оба способа (с указанием опции -f или без) запустят файл my_script.php . Нет ограничений, какой файл запускать; в частности, файлы не обязаны иметь расширение .php .
Если необходимо передать аргументы в скрипт, то при использовании опции -f первым аргументом должен быть — .
Передать PHP-код напрямую в командной строке.
Необходимо быть особо осторожным при использовании этого способа, т.к. может произойти подстановка переменных оболочки при использовании двойных кавычек.
Внимательно прочтите пример: в нем нет открывающих и закрывающих тегов! Опция -r просто в них не нуждается, и их использование приведёт к ошибке разбора.
Передать запускаемый PHP-код через стандартный поток ввода ( stdin ).
Это даёт мощную возможность создавать PHP-код и передавать его запускаемому файлу, как показано в этом (вымышленном) примере:
Как и любое другое консольное приложение, бинарный файл PHP принимает аргументы, но PHP-скрипт также может получать аргументы. PHP не ограничивает количество аргументов, передаваемых в скрипт (оболочка консоли устанавливает некоторый порог количества символов, которые могут быть переданы; обычно этого лимита хватает). Переданные аргументы доступны в глобальном массиве $argv . Первый индекс (ноль) всегда содержит имя вызываемого скрипта из командной строки. Учтите, что если код вызывается на лету из командной строки с помощью опции -r, значением $argv[0] будет просто дефис ( — ). То же самое верно и для кода, переданного через конвейер из STDIN .
Вторая зарегистрированная глобальная переменная — это $argc , содержащая количество элементов в массиве $argv (а не количество аргументов, переданных скрипту).
Если передаваемые аргументы не начинаются с символа — , то особых проблем быть не должно. Передаваемый в скрипт аргумент, который начинается с — создаст проблемы, т.к. PHP решит, что он сам должен его обработать. Для предотвращения подобного поведения используйте разделитель списка аргументов — . После того, как этот разделитель будет проанализирован PHP, все последующие аргументы будут переданы в скрипт нетронутыми.
Пример #1 Запуск PHP-скрипта как консольного
Предполагая, что этот файл назван test и находится в текущей директории, можно сделать следующее:
Как можно увидеть, в этом случае не нужно заботиться о передаче параметров, которые начинаются с — .
Исполняемый PHP-файл может использоваться для запуска PHP-скриптов независимо от веб-сервера. В случае работы в Unix-подобной системе, необходимо добавить в первую строку файла #! (называемый также «shebang») чтобы указать, какая из программ должна запускать скрипт. На Windows-платформах можно назначить обработчик php.exe для файлов с расширениями .php или создать пакетный (.bat) файл для запуска скриптов посредством PHP. Строка, добавляемая в начале скрипта для Unix-систем, не влияет на их работу в ОС Windows, таким образом можно создавать кроссплатформенные скрипты. Ниже приведён простой пример скрипта, выполняемого из командной строки:
Пример #2 Скрипт, предназначенный для запуска из командной строки (script.php)
#!/usr/bin/php
if ( $argc != 2 || in_array ( $argv [ 1 ], array( ‘—help’ , ‘-help’ , ‘-h’ , ‘-?’ ))) <
?>
Это консольный PHP-скрипт, принимающий один аргумент.
Использование:
echo $argv [ 0 ]; ?>
Любое слово, которое вы хотели бы
напечатать. Опции —help, -help, -h,
или -? покажут текущую справочную информацию.
В приведённом выше скрипте в первой строке содержится shebang, указывающий что этот файл должен запускаться PHP. Работа ведётся с CLI -версией, поэтому не будет выведено ни одного HTTP -заголовка.
Скрипт сначала проверяет наличие обязательного одного аргумента (в дополнение к имени скрипта, который также подсчитывается). Если их нет, или если переданный аргумент был —help, -help, -h или -?, выводится справочное сообщение с использованием $argv[0] , которое содержит имя выполняемого скрипта. В противном случае просто выводится полученный аргумент.
Для запуска приведённого примера в Unix-системе, нужно сделать его исполняемым и просто выполнить в консоли script.php echothis или script.php -h. В Windows-системе можно создать пакетный файл:
Пример #3 Пакетный файл для запуска PHP-скрипта из командной строки (script.bat)
Также можно ознакомиться с модулем Readline для получения дополнительных функций, которые можно использовать для улучшения консольного PHP-скрипта.
В Windows запуск PHP можно настроить без необходимости указывать C:\php\php.exe или расширение .php . Подробнее эта тема описана в разделе Запуск PHP из командной строки в Microsoft Windows.
В Windows рекомендуется запускать PHP под актуальной учётной записью пользователя. При работе в сетевой службе некоторые операции не будут выполнены, поскольку «сопоставление имён учётных записей и идентификаторов безопасности не выполнено».
User Contributed Notes 7 notes
On Linux, the shebang (#!) line is parsed by the kernel into at most two parts.
For example:
1: #!/usr/bin/php
2: #!/usr/bin/env php
3: #!/usr/bin/php -n
4: #!/usr/bin/php -ddisplay_errors=E_ALL
5: #!/usr/bin/php -n -ddisplay_errors=E_ALL
1. is the standard way to start a script. (compare «#!/bin/bash».)
2. uses «env» to find where PHP is installed: it might be elsewhere in the $PATH, such as /usr/local/bin.
3. if you don’t need to use env, you can pass ONE parameter here. For example, to ignore the system’s PHP.ini, and go with the defaults, use «-n». (See «man php».)
4. or, you can set exactly one configuration variable. I recommend this one, because display_errors actually takes effect if it is set here. Otherwise, the only place you can enable it is system-wide in php.ini. If you try to use ini_set() in your script itself, it’s too late: if your script has a parse error, it will silently die.
5. This will not (as of 2013) work on Linux. It acts as if the whole string, «-n -ddisplay_errors=E_ALL» were a single argument. But in BSD, the shebang line can take more than 2 arguments, and so it may work as intended.
Summary: use (2) for maximum portability, and (4) for maximum debugging.
Источник
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 in console linux
Используя интерактивную консоль, можно ввести и выполнить непосредственно PHP-код.
Пример #1 Запуск кода в интерактивной консоли
Интерактивная консоль также автодополняет (с помощью клавиши Tab) имена функций, констант, классов, переменных, вызовы статических методов и константы классов.
Пример #2 Автодополнение по Tab
Двойное нажатие клавиши Tab при наличии нескольких вариантов дополнения покажет список этих вариантов:
Когда есть только одно дополнение, одиночное нажатие Tab дополнит оставшийся текст на той же самой строке:
Дополнение также работает для имён, которые были объявлены в течение данной интерактивной сессии:
Интерактивная консоль хранит историю команд, для доступа к которой можно использовать стрелки вверх и вниз. История хранится в файле
Также можно устанавливать настройки php.ini в интерактивной консоли, используя специальное сокращение.
Пример #3 Установка настройки php.ini в интерактивной консоли
Используя обратные апострофы можно задать PHP-код, который выполнится в приглашении на ввод команды:
Установка less для постраничного вывода данных:
Настройка cli.prompt поддерживает несколько управляющих последовательностей:
Управляющая последовательность | Описание |
---|---|
\e | Используется для добавления цветов в приглашение на ввод команды. Пример: \e[032m\v \e[031m\b \e[34m\> \e[0m |
\v | Версия PHP. |
\b | Отображает в какой части PHP мы находимся. Для примера /* показывает, что мы находимся в многострочном комментарии. Внешняя область видимости обозначается как php . |
\> | Указывает символ приглашения. По умолчанию это символ > , но можно изменить, когда оболочка находится внутри незакрытого блока или строки. Возможные символы: ‘ « |
Файлы, подключённые с помощью опций auto_prepend_file и auto_append_file обрабатываются в этом режиме с некоторыми ограничениями, например, функции должны быть объявлены до их использования.
User Contributed Notes 14 notes
Interactive Shell and Interactive Mode are not the same thing, despite the similar names and functionality.
If you type ‘php -a’ and get a response of ‘Interactive Shell’ followed by a ‘php>’ prompt, you have interactive shell available (PHP was compiled with readline support). If instead you get a response of ‘Interactive mode enabled’, you DO NOT have interactive shell available and this article does not apply to you.
You can also check ‘php -m’ and see if readline is listed in the output — if not, you don’t have interactive shell.
Interactive mode is essentially like running php with stdin as the file input. You just type code, and when you’re done (Ctrl-D), php executes whatever you typed as if it were a normal PHP (PHTML) file — hence you start in interactive mode with ‘
In Windows, press Enter after your ending PHP tag and then hit Ctrl-Z to denote the end-of-file:
C:\>php -a
Interactive mode enabled
echo «Hello, world!» ;
?>
^Z
Hello, world!
You can use the up and down arrows in interactive mode to recall previous code you ran.
It seems the interactive shell cannot be made to work in WIN environments at the moment.
Using «php://stdin», it shouldn’t be too difficult to roll your own. You can partially mimic the shell by calling this simple script (Note: Window’s cmd already has an input history calling feature using the up/down keys, and that functionality will still be available during execution here):
= fopen ( «php://stdin» , «r» );
$in = » ;
while( $in != «quit» ) <
echo «php> » ;
$in = trim ( fgets ( $fp ));
eval ( $in );
echo «\n» ;
>
?>
Replace ‘eval’ with code to parse the input string, validate it using is_callable and other variable handling functions, catch fatal errors before they happen, allow line-by-line function defining, etc. Though Readline is not available in Windows, for more tips and examples for workarounds, see http://www.php.net/manual/en/ref.readline.php
For use interactive mode enabled on GNU/Linux on distros Debian/Ubuntu/LinuxMint you must install «php*-cli» and «php*-readline» packages from official repository.
Example:
>$sudo aptitude install php5-cli php5-readline
After that you can use interactive mode.
Example:
$ php -a
Interactive mode enabled
php >echo «hola mundo!\n»;
hola mundo!
php >
I hope somebody help it!
Just a few more notes to add.
1) Hitting return does literally mean «execute this command». Semicolon to note end of line is still required. Meaning, doing the following will produce a parse error:
php > print «test»
php > print «asdf»;
Whereas doing the following is just fine:
php > print «test»
php > .»asdf»;
2) Fatal errors may eject you from the shell:
Fatal Error: call to undefined function.
name@local:
3) User defined functions are not saved in history from shell session to shell session.
4) Should be obvious, but to quit the shell, just type «quit» at the php prompt.
5) In a sense, the shell interaction can be thought of as linearly following a regular php file, except it’s live and dynamic. If you define a function that you’ve already defined earlier in your current shell, you will receive a fatal «function already defined» error only upon entering that closing bracket. And, although «including» a toolset of custom functions or a couple of script addon php files is rather handy, should you edit those files and wish to «reinclude» it again, you’ll cause a fatal «function x already defined» error.
Источник