Usr bin php f что означает
Перейти к содержимому

Usr bin php f что означает

  • автор:

Sorry, you have been blocked

This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.

What can I do to resolve this?

You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.

Cloudflare Ray ID: 7a707931ef5a2479 • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare

Как использовать и выполнять PHP-коды в командной строке Linux — Часть 1

PHP — это язык сценариев на стороне сервера с открытым исходным кодом, который первоначально означал «Персональная домашняя страница», а теперь означает «PHP: Препроцессор гипертекста», что является рекурсивной аббревиатурой. Это кроссплатформенный язык сценариев, на который сильно повлияли C, C ++ и Java.

Синтаксис PHP очень похож на синтаксис в языках программирования C, Java и Perl с некоторыми особенностями, специфичными для PHP. На данный момент PHP используется примерно 260 миллионами веб-сайтов. Текущий стабильный выпуск — PHP версии 5.6.10.

PHP — это встроенный скрипт HTML, который помогает разработчикам быстро писать динамически генерируемые страницы. PHP в основном используется на стороне сервера (и JavaScript на стороне клиента) для создания динамических веб-страниц через HTTP, однако вы будете удивлены, узнав, что вы можете выполнять PHP в терминале Linux без использования веб-браузера.

Эта статья направлена на то, чтобы пролить свет на аспект командной строки языка сценариев PHP.

1. После установки PHP и Apache2 нам необходимо установить интерпретатор командной строки PHP.

Следующее, что мы делаем, это обычно тестируем php (если он установлен правильно или нет), например, создавая файл infophp.php в местоположении ‘/ var/www/html’ (рабочий каталог Apache2 в большинстве дистрибутивы) с содержимым , просто выполнив команду ниже.

а затем укажите в браузере http://127.0.0.1/infophp.php, который откроет этот файл в веб-браузере.

Такие же результаты можно получить из терминала Linux без необходимости использования какого-либо браузера. Запустите файл PHP, расположенный по адресу «/var/www/html/infophp.php» в командной строке Linux, как:

Поскольку вывод слишком велик, мы можем конвейеризовать приведенный выше вывод с помощью команды «less», чтобы выводить по одному экрану за раз, просто как:

Здесь опция «-f» анализирует и выполняет файл, следующий за командой.

2. Мы можем использовать phpinfo() , который является очень ценным инструментом отладки, непосредственно в командной строке Linux без необходимости вызывать его из файла, просто как:

Здесь опция «-r» запускает PHP-код в терминале Linux напрямую без тегов и > .

3. Запустите PHP в интерактивном режиме и выполните некоторые математические вычисления. Здесь опция «-a» предназначена для запуска PHP в интерактивном режиме.

Нажмите «exit» или «ctrl+c», чтобы закрыть интерактивный режим PHP.

4. Вы можете запустить сценарий PHP просто, как если бы это был сценарий оболочки. Сначала создайте образец сценария PHP в вашем текущем рабочем каталоге.

Обратите внимание, что мы использовали #!/Usr/bin/php в первой строке этого PHP-скрипта, как мы это делаем в скрипте оболочки (/ bin/bash). Первая строка #!/Usr/bin/php сообщает командной строке Linux о необходимости синтаксического анализа этого файла сценария интерпретатору PHP.

Во-вторых, сделайте его исполняемым как:

и запустите его как,

5. Вы будете удивлены, узнав, что вы можете создавать простые функции самостоятельно, используя интерактивную оболочку. Вот пошаговая инструкция.

Запустите интерактивный режим PHP.

Создайте функцию и назовите ее добавлением. Также объявите две переменные $a и $b.

Используйте фигурные скобки, чтобы определить правила между ними для этой функции.

Определите правила. Здесь правило говорит, что нужно сложить две переменные.

Все правила определены. Заключите правила, закрыв фигурные скобки.

Протестируйте функцию и добавьте цифры 4 и 3 просто как:

Вы можете запускать приведенный ниже код для выполнения функции сколько угодно раз с разными значениями. Замените a и b своими значениями.

Вы можете запускать эту функцию, пока не выйдете из интерактивного режима (Ctrl + z). Также вы могли заметить, что в приведенном выше выводе возвращаемый тип данных — NULL. Это можно исправить, попросив интерактивную оболочку php вернуть вместо echo.

Просто замените оператор «echo» в приведенной выше функции на «return».

а в остальном вещи и принципы остаются прежними.

Вот пример, который возвращает соответствующий тип данных на выходе.

Всегда помните, что пользовательские функции не сохраняются в истории от сеанса оболочки к сеансу оболочки, поэтому после выхода из интерактивной оболочки она теряется.

Надеюсь, вам понравился этот сеанс. Оставайтесь на связи, чтобы получать больше таких сообщений. Оставайтесь с нами и будьте здоровы. Оставьте нам свой ценный отзыв в комментариях. Как и мы, поделитесь нами и помогите нам распространиться.

Usr bin php f что означает

Tell PHP to execute a certain file.

Both ways (whether using the -f switch or not) execute the file my_script.php . Note that there is no restriction on which files can be executed; in particular, the filename is not required have a .php extension.

Pass the PHP code to execute directly on the command line.

Special care has to be taken with regard to shell variable substitution and usage of quotes.

Note:

Read the example carefully: there are no beginning or ending tags! The -r switch simply does not need them, and using them will lead to a parse error.

Provide the PHP code to execute via standard input ( stdin ).

This gives the powerful ability to create PHP code dynamically and feed it to the binary, as shown in this (fictional) example:

As with every shell application, the PHP binary accepts a number of arguments; however, the PHP script can also receive further arguments. The number of arguments that can be passed to your script is not limited by PHP (and although the shell has a limit to the number of characters which can be passed, this is not in general likely to be hit). The arguments passed to the script are available in the global array $argv . The first index (zero) always contains the name of the script as called from the command line. Note that, if the code is executed in-line using the command line switch -r, the value of $argv[0] will be "Standard input code" ; prior to PHP 7.2.0, it was a dash ( "-" ) instead. The same is true if the code is executed via a pipe from STDIN .

A second global variable, $argc , contains the number of elements in the $argv array (not the number of arguments passed to the script).

As long as the arguments to be passed to the script do not start with the — character, there's nothing special to watch out for. Passing an argument to the script which starts with a — will cause trouble because the PHP interpreter thinks it has to handle it itself, even before executing the script. To prevent this, use the argument list separator — . After this separator has been parsed by PHP, every following argument is passed untouched to the script.

Example #1 Execute PHP script as shell script

Assuming this file is named test in the current directory, it is now possible to do the following:

As can be seen, in this case no special care needs to be taken when passing parameters starting with — .

The PHP executable can be used to run PHP scripts absolutely independent of the web server. On Unix systems, the special #! (or "shebang") first line should be added to PHP scripts so that the system can automatically tell which program should run the script. On Windows platforms, it's possible to associate php.exe with the double click option of the .php extension, or a batch file can be created to run scripts through PHP. The special shebang first line for Unix does no harm on Windows (as it's formatted as a PHP comment), so cross platform programs can be written by including it. A simple example of writing a command line PHP program is shown below.

Example #2 Script intended to be run from command line (script.php)

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

This is a command line PHP script with one option.

Usage:
<?php echo $argv [ 0 ]; ?> <option>

<option> can be some word you would like
to print out. With the —help, -help, -h,
or -? options, you can get this help.

The script above includes the Unix shebang first line to indicate that this file should be run by PHP. We are working with a CLI version here, so no HTTP headers will be output.

The program first checks that there is the required one argument (in addition to the script name, which is also counted). If not, or if the argument was —help, -help, -h or -?, the help message is printed out, using $argv[0] to dynamically print the script name as typed on the command line. Otherwise, the argument is echoed out exactly as received.

To run the above script on Unix, it must be made executable, and called simply as script.php echothis or script.php -h. On Windows, a batch file similar to the following can be created for this task:

Example #3 Batch file to run a command line PHP script (script.bat)

See also the Readline extension documentation for more functions which can be used to enhance command line applications in PHP.

On Windows, PHP can be configured to run without the need to supply the C:\php\php.exe or the .php extension, as described in Command Line PHP on Microsoft Windows.

Note:

On Windows it is recommended to run PHP under an actual user account. When running under a network service certain operations will fail, because "No mapping between account names and security IDs was done".

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.

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 <?php phpinfo(); ?> , 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

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.

Tutorial Feedback.

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.

Support Us

We are thankful for your never ending support.

Related Posts

Linux PHP Hardening Security Tips

Install OPcache in Debian and Ubuntu

Install PHP 7.4 in Rocky Linux

Install PHP 8.0 on Rocky Linux

Improve PHP-FPM Performance

Install Different PHP Versions in Ubuntu

5 thoughts on “How to Use and Execute PHP Codes in Linux Command Line – Part 1”

As I’m facing an issue with the php scripts which are not executing in the web browsers, request your suggestion for the same.

Here I’m attaching the scripts for your better understanding

Just type it in command line.
php -r ‘echo «hello world!»;’

when after creating the file info.php and I execute it I get the code back instead of its execution:

I liked the article, am about to read the 2nd in the series.

this line
< >
is a little confusing, perhaps it should be
Next thing, we do is to test to see if php is installed correctly or not. We can do this by creating a file

Thanks for the hard work publishing these,

I have long been used as the php scripting language for command line. I would like the development of this article. thanks.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *