Linux usr bin php

How to add shebang #! with php script on linux?

I’m having a little issue with adding shebang #! with my php script on RedHat linux. I have a small piece of test code with shebang added (I’ve tried different variations as well), but I get the following error message everytime I try to run the script. Error msg:

-bash: script.php: command not found 

@JoelFan — people have the freedom to express their silly thoughts on blogs, don’t do it on a site where we help other developers. Thank you. To answer the question about the error — it’s most likely because of CR\LF combination that comes after your first line. Use hex editor to check whether you have \n\r and if yes, remove carriage return. CHMOD +x yourfile.php to make it executable too.

5 Answers 5

It should (for most systems) be #!/usr/bin/env php , but your error isn’t related to that.

-bash: script.php: command not found 

It says that script.php is not found.

If the problem was the shebang line then the error would say something like:

bash: script.php: /usr/env: bad interpreter: No such file or directory 

Presumably, you are typing script.php and the file is not in a directory on your $PATH or is not executable.

  1. Make it executable: chmod +x script.php .
  2. Type the path to it instead of just the filename, if it is in the current directory then: ./script.php .

Instead of 2, you can move/copy/symlink the file to somewhere listed in $PATH or modify the $PATH to include the directory containing the script.

Источник

Выполнение PHP-файлов

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

$ php my_script.php $ php -f my_script.php

Оба способа (с указыванием опции -f или без) запустят файл my_script.php . Нет ограничений, какой файл запускать, и PHP-скрипты не обязаны иметь расширение .php.

Замечание: Если необходимо передать аргументы в скрипт, то при использовании опции -f первым аргументом должен быть .

$ 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] будет просто дефис (). То же самое верно и для кода, переданного через конвейер из STDIN.

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

Читайте также:  What can linux do better than windows

Если передаваемые аргументы не начинаются с символа , то особых проблем быть не должно. Передаваемый в скрипт аргумент, который начинается с создаст проблемы, так как 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-скрипт:

Пример #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,
или -? покажут текущую справочную информацию.

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

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

Читайте также:  Посмотреть версию python linux

Для запуска приведенного примера в 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.

Источник

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

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.

# apt-get install php5-cli [Debian and alike System) # yum install php-cli [CentOS and alike System)

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.

# echo '' > /var/www/html/infophp.php

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:

# php -f /var/www/html/infophp.php

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:

# php -f /var/www/html/infophp.php | less

Check All PHP Info

Here Option ‘-f‘ parse and execute the file that follows the command.

Читайте также:  Проверить работает ли postgresql linux

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.

# php -a Interactive shell php > echo 2+3; 5 php > echo 9-6; 3 php > echo 5*4; 20 php > echo 12/3; 4 php > echo 12/5; 2.4 php > echo 2+3-1; 4 php > echo 2+3-1*3; 2 php > exit

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.

# echo -e '#!/usr/bin/php\n' > phpscript.php

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.

php > function addition ($a, $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 :

php > var_dump (addition(4,3));
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.

php > var_dump (addition(a,b));
php > var_dump (addition(9,3.3));
Sample Output

Create PHP Functions

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.

Источник

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