Ubuntu как запустить php скрипт

Как запустить PHP-скрипт через командную строку?

Для чего нужен запуск php-скриптов через командную строку? Он позволяет проверить и отладить работу скриптов на новой версии PHP или с иными значениями PHP-директив, не меняя их для всего сайта целиком (например, если на более высокой версии PHP скрипт работает некорректно, то его запуск через консоль не нарушит работу сайта, что может произойти если сменить версию на самом сайте).

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

Подключить SSH-доступ

1. Чтобы иметь возможность запустить PHP скрипт из командной строки, необходимо иметь услугу хостинга с активным SSH-доступом. Проверить, активен ли SSH-доступ у Вас, можно в панели хостинга в разделе «Инструменты». Если при открытии данного раздела есть пункт «Shell-клиент», то SSH-доступ на Вашей услуге хостинга открыт.

Shell-клиент в панели управления ISPmanager

Если же такого пункта нет, то Вам нужно через личный аккаунт создать запрос в службу поддержки, чтобы данный доступ предоставили. Как создать запрос в техподдержку, читайте на нашем сайте.

Подключение по SSH

2. После получения SSH-доступа, подключимся к нашей услуге через любой SSH-клиент.

Либо можно использовать Shell-клиент из панели хостинга, но он не совсем удобен, для тех случаев, когда команды требуется откуда-то копировать и затем вставлять в консоль.

Команды для подключения через терминал Linux или утилиту PowerShell Windows будет иметь следующий вид:

ssh -p 34716 логин@имя или IP-адрес сервера.

Логином служит имя пользователя от панели хостинга.

Примеры:
ssh -p 34716 usertest@fry.handyhost.ru

Подключение по SSH

ssh -p 34716 usertest@109.95.210.219

После подключения можем приступать к запуску.

Запуск PHP-скрипта

3. Самый простой вариант — команда вида php/путь/к/скрипту. Такая команда запустит указанный Вами скрипт через нативную версию PHP (системную версию PHP, которая по умолчанию устанавливалась для ОС сервера с Вашей услугой хостинга), с теми настройками, которые установлены на сервере по умолчанию.

Пример:
php /var/www/usertest/data/www/fryhh.onhh.ru/info.php Как запустить PHP-скрипт на хостинге через терминал
Узнать какая версия PHP используется по умолчанию на сервер с Вашей услугой можно командой: php -v
Как узнать какая версия PHP на хостинге в терминале

В данном примере версией PHP, используемой по умолчанию является версия 7.3.

4. Для запуска через конкретную версию PHP указать в нашей команде путь к сборке PHP соответствующей версии. Команда будет иметь вид:
/opt/alt/phpXX/usr/bin/php/путь/к/скрипту
Примеры:
/opt/alt/php53/usr/bin/php /var/www/usertest/data/www/fryhh.onhh.ru/info.php
/opt/alt/php72/usr/bin/php /var/www/usertest/data/www/fryhh.onhh.ru/info.php
/opt/alt/php81/usr/bin/php /var/www/usertest/data/www/fryhh.onhh.ru/info.php
Список доступных сборок:
/opt/alt/php51/usr/bin/php
/opt/alt/php52/usr/bin/php
/opt/alt/php53/usr/bin/php
/opt/alt/php54/usr/bin/php
/opt/alt/php55/usr/bin/php
/opt/alt/php56/usr/bin/php
/opt/alt/php70/usr/bin/php
/opt/alt/php71/usr/bin/php
/opt/alt/php72/usr/bin/php
/opt/alt/php73/usr/bin/php
/opt/alt/php74/usr/bin/php
/opt/alt/php80/usr/bin/php
/opt/alt/php81/usr/bin/php
На скриншоте запуск скрипта через версию PHP 5.1.

запуск скрипта через версию PHP 5.1 в терминале

5. Важно — если в настройки той версии PHP, через которую запускается скрипт, были внесены изменения через панель хостинга, то скрипт также запустится с этими настройками PHP. Как поменять настройки php.ini, читайте в нашей статье.

Читайте также:  Java run app for android

Скрипт, используемый в качестве примера в данной статье, выводит информацию о версии и настройках PHP, через которые он запущен.

На скриншоте показаны результаты его запуска через нативную версию PHP 7.4, для которой значение параметра memory_limit менялось и версию PHP 7.2, для которой изменения настроек не производилось (к результатам работы применен фильтр через функцию grep по параметру memory_limit).

результаты запуска скрипта через нативную версию PHP 7.4 в терминале

Если нам по каким-то причинам требуется запустить скрипт через определенную версию PHP с настройками, отличающимися от тех, что заданы для этой версии через панель, то можно использовать опцию -n — не будут учитываться никакие ini-файлы и соответственно внесенные через панель изменения, либо опцию -d для переопределения конкретной директивы.

Примеры:
/opt/alt/php74/usr/bin/php -d memory_limit=1000M /var/www/usertest/data/www/fryhh.onhh.ru/info.php

результаты запуска скрипта через PHP 7.4 с memory_limit на 350 Мб

/opt/alt/php74/usr/bin/php -n /var/www/usertest/data/www/fryhh.onhh.ru/info.php

На скриншоте показаны результаты запуска скрипта через PHP 7.4, для которой значений параметра memory_limit установлено на 350 Мб через панель хостинга. Запуск производился с опцией -n, опцией -d memory_limit=1000M, которая устанавливает значение параметра memory_limit на 1000 Мб и без дополнительных опций. К результатам вывода также применен фильтр через функцию grep по параметру memory_limit.

Источник

Ubuntu как запустить php скрипт

    Tell PHP to execute a certain file.

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

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.

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

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.

# This will not execute the given code but will show the PHP usage $ php -r 'var_dump($argv);' -h Usage: php [options] [-f] [args. ] [. ] # This will pass the '-h' argument to the script and prevent PHP from showing its usage $ php -r 'var_dump($argv);' -- -h array(2) < [0]=>string(1) "-" [1]=> string(2) "-h" >

However, on Unix systems there’s another way of using PHP for shell scripting: make the first line of the script start with #!/usr/bin/php (or whatever the path to your PHP CLI binary is if different). The rest of the file should contain normal PHP code within the usual PHP starting and end tags. Once the execution attributes of the file are set appropriately (e.g. chmod +x test), the script can be executed like any other shell or perl script:

Читайте также:  Python передача объекта объекту

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:

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

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.

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.

Читайте также:  Css grid first row

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)

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

Assuming the above program is named script.php , and the CLI php.exe is in C:\php\php.exe , this batch file will run it, passing on all appended options: script.bat echothis or script.bat -h.

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».

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.

Источник

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