Php bin bash скрипт

Php bin bash скрипт

    Указание конкретного файла для запуска.

$ php my_script.php $ php -f my_script.php
$ php -r 'print_r(get_defined_constants());'

Необходимо быть особо осторожным при использовании этого способа, т.к. может произойти подстановка переменных оболочки при использовании двойных кавычек.

Замечание: Внимательно прочтите пример: в нем нет открывающих и закрывающих тегов! Опция -r просто в них не нуждается, и их использование приведёт к ошибке разбора.

$ some_application | some_filter | php | sort -u > final_output.txt

Как и любое другое консольное приложение, бинарный файл PHP принимает аргументы, но PHP-скрипт также может получать аргументы. PHP не ограничивает количество аргументов, передаваемых в скрипт (оболочка консоли устанавливает некоторый порог количества символов, которые могут быть переданы; обычно этого лимита хватает). Переданные аргументы доступны в глобальном массиве $argv . Первый индекс (ноль) всегда содержит имя вызываемого скрипта из командной строки. Учтите, что если код вызывается на лету из командной строки с помощью опции -r, значением $argv[0] будет «Стандартный поток» («Standard input code»); до PHP 7.2.0 это был дефис ( «-» ). То же самое верно и для кода, переданного через конвейер из STDIN .

Вторая зарегистрированная глобальная переменная — это $argc , содержащая количество элементов в массиве $argv (а не количество аргументов, переданных скрипту).

Если передаваемые аргументы не начинаются с символа — , то особых проблем быть не должно. Передаваемый в скрипт аргумент, который начинается с — создаст проблемы, т.к. PHP решит, что он сам должен его обработать. Для предотвращения подобного поведения используйте разделитель списка аргументов — . После того, как этот разделитель будет проанализирован PHP, все последующие аргументы будут переданы в скрипт нетронутыми.

# Эта команда не запустит данный код, но покажет информацию об использовании PHP $ php -r 'var_dump($argv);' -h Usage: php [options] [-f] [args. ] [. ] # Эта команда передаст аргумент '-h' в скрипт, предотвратив показ справки PHP $ php -r 'var_dump($argv);' -- -h array(2) < [0]=>string(1) "-" [1]=> string(2) "-h" >

Однако, в Unix-системах есть ещё один способ использования PHP для консольных скриптов. Можно написать скрипт, первая строка которого будет начинаться с #!/usr/bin/php (или же другой корректный путь к бинарному файлу PHP CLI ). После этой строки можно поместить обычный PHP-код, заключённый в открывающие и закрывающие теги PHP. Как только будут установлены корректные атрибуты запуска на файл (например, chmod +x test), скрипт может быть запущен как обычный консольный или perl-скрипт:

Читайте также:  Javascript is lower than

Пример #1 Запуск PHP-скрипта как консольного

Предполагая, что этот файл назван test и находится в текущей директории, можно сделать следующее:

$ chmod +x test $ ./test -h -- foo array(4) < [0]=>string(6) "./test" [1]=> string(2) "-h" [2]=> string(2) "--" [3]=> string(3) "foo" >

Как можно увидеть, в этом случае не нужно заботиться о передаче параметров, которые начинаются с — .

Исполняемый PHP-файл может использоваться для запуска PHP-скриптов независимо от веб-сервера. В случае работы в Unix-подобной системе, необходимо добавить в первую строку файла #! (называемый также «shebang») чтобы указать, какая из программ должна запускать скрипт. На Windows-платформах можно назначить обработчик php.exe для файлов с расширениями .php или создать пакетный (.bat) файл для запуска скриптов посредством PHP. Строка, добавляемая в начале скрипта для Unix-систем, не влияет на их работу в ОС Windows, таким образом можно создавать кроссплатформенные скрипты. Ниже приведён простой пример скрипта, выполняемого из командной строки:

Пример #2 Скрипт, предназначенный для запуска из командной строки (script.php)

if ( $argc != 2 || in_array ( $argv [ 1 ], array( ‘—help’ , ‘-help’ , ‘-h’ , ‘-?’ ))) ?>

Это консольный PHP-скрипт, принимающий один аргумент.

Любое слово, которое вы хотели бы
напечатать. Опции —help, -help, -h,
или -? покажут текущую справочную информацию.

В приведённом выше скрипте в первой строке содержится shebang, указывающий что этот файл должен запускаться PHP. Работа ведётся с CLI -версией, поэтому не будет выведено ни одного HTTP -заголовка.

Скрипт сначала проверяет наличие обязательного одного аргумента (в дополнение к имени скрипта, который также подсчитывается). Если их нет, или если переданный аргумент был —help, -help, -h или -?, выводится справочное сообщение с использованием $argv[0] , которое содержит имя выполняемого скрипта. В противном случае просто выводится полученный аргумент.

Для запуска приведённого примера в Unix-системе, нужно сделать его исполняемым и просто выполнить в консоли script.php echothis или script.php -h. В Windows-системе можно создать пакетный файл:

Пример #3 Пакетный файл для запуска PHP-скрипта из командной строки (script.bat)

@echo OFF "C:\php\php.exe" script.php %*

Предполагая, что вышеприведённый скрипт называется script.php , а полный путь к CLI php.exe находится в C:\php\php.exe , этот пакетный файл запустит его с переданными параметрами: script.bat echothis или script.bat -h.

Также можно ознакомиться с модулем 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.

Источник

Execute Shell Command in PHP using exec()

The PHP script is mainly used for developing web applications but it can be used for other purposes also. PHP has some built-in functions to execute system-related commands. exec() is one of them. It is used to execute shell commands or any program from the PHP script. How this function can be used in PHP are shown in this tutorial.

Syntax:

This function can take three arguments. The first argument is mandatory that will take the system command. The other two arguments are optional. The second argument is used to store the output of the command in an array. The third argument of this function is used to store the return status of the executed command. This function returns the last line from the executed command output.

Example-1: Use of exec() function without optional arguments

The basic use of the exec() function has shown in this tutorial. Create a PHP file with the following script to know how the exec() function returns the command output. ‘pwd‘ command has used in the first exec()command of the script that returns one line of output. ‘ls -la‘ command has been used in the second exec() command that can return multiple lines of output. If any command returns multiple lines then the output will show the last line as the output.

//Store the output of the executed command

//Store the last line of the executed command

The following output will appear after running the above script from the server. ‘pwd‘ command returns the current working directory as output that is shown in the first output. ‘ls -la‘ command returns the details information of the list of directories and the second output shows the last line from the command output.

Example-2: Print all values of the executed command

In the previous example, no optional argument is used in the exec() function. The following example shows the use of optional arguments of the exec() function. Create a PHP file with the following script. Two optional arguments of exec() are used in this script. ‘ls -l‘ command is used in the first argument that returns the list of directories. $output variable is used here to store the output of the command in an array. $status variable is used to store the return status value of the executed command. The output of the command will be printed as an array and each value of the output array will be printed by using the ‘for’ loop.

//Store the output of the executed command in an array

//Print all return values of the executed command as array

//Print the output of the executed command in each line

//Print the return status of the executed command

The following output will appear after running the above script from the server. The output shows the array that contains the output of the command, ‘ls -l’ and each value of the array in each line.

Example-3: Print all PHP files of the current directory

The following example shows the list of all PHP files of the current directory by using the exec() function. Here, the ‘ls -l *.php‘ command is used here to find out the list of all PHP files of the current directory. tag is used in the script to print the content of the array with the structured format.

//Store the output of the executed command in an array

//Print the output of the executed command

The following output will appear after running the above script from the server.

Example-4: Run a bash script

How any bash script can be executed by using the exec() function has shown in this example. Create a bash file named loop.sh with the following script that will print all even numbers from 1 to 20.

#!/bin/bash

#Initialize the counter

counter = 1

#Iterate the loop until the $counter value is less than or equal to 20

while [ $counter — le 20 ]

#Print the even numbers

if [ [ $counter % 2 — eq 0 ] ]

#Print $counter without newline

echo » $counter «

#Increment $counter by 1

( ( counter ++ ) )

Create a PHP file with the following script to run the bash script. ‘bash loop.sh‘ is used as the first argument of the exec() function that will execute the loop.sh script file. ‘foreach‘ loop is used to print each value of the $output with space.

echo «All even numbers within 1-20 are:
» ;

//Print the ourput using loop

The following output will appear after running the above script from the server. The output shows all even numbers within 1 to 20.

Example-5 : Run `dir` command using exec() function

‘dir’ command works like the ‘ls’ command. The following example shows how the ‘dir’ command can be executed using a PHP script. Create a PHP file with the following script that stores the output of the ‘dir’ command in the array named $output and the status value in the variable named $return. var_dump() function is used here to print the structure of the $output array with the data type information.

//Print the return status value

echo «The return value of the `dir` command is $return \n » ;

The following output will appear after running the above script from the server.

Conclusion:

Different uses of the exec() function have been explained in this tutorial to help the PHP coders to know the way to execute the shell command by using the PHP script. Some other functions also exist in PHP to do the same type of task.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Оцените статью