Php to executable linux

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.

Читайте также:  Чем хороша операционная система mac os

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 to executable linux

There are three different ways of supplying the CLI SAPI with PHP code to be executed:

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.

If arguments need to be passed to the script when using -f, the first argument must be — .

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.

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 just a dash ( — ). 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.

Читайте также:  Отключение windows defender через gpedit

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

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

This is a command line PHP script with one option.

Usage:
echo $argv [ 0 ]; ?>

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.

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.

Источник

How can I execute PHP code from the command line?

I would like to execute a single PHP statement like if(function_exists(«my_func»)) echo ‘function exists’; directly with the command line without having to use a separate PHP file.

How is it possible?

6 Answers 6

If you’re going to do PHP in the command line, I recommend you install phpsh, a decent PHP shell. It’s a lot more fun.

Anyway, the php command offers two switches to execute code from the command line:

You can use php ‘s -r switch as such:

The above PHP command above should output no and returns 0 as you can see:

Another funny switch is php -a:

It’s sort of lame compared to phpsh, but if you don’t want to install the awesome interactive shell for PHP made by Facebook to get tab completion, history, and so on, then use -a as such:

Читайте также:  Основные понятия windows графический интерфейс

If it doesn’t work on your box like on my boxes (tested on Ubuntu and Arch Linux), then probably your PHP setup is fuzzy or broken. If you run this command:

You should see:

If you don’t, this means that maybe another command will provides the CLI SAPI. Try php-cli; maybe it’s a package or a command available in your OS.

If you do see that your php command uses the CLI (command-line interface) SAPI (Server API), then run php -h | grep code to find out which crazy switch — as this hasn’t changed for year- allows to run code in your version/setup.

Another couple of examples, just to make sure it works on my boxes:

Источник

Системные скрипты на php для linux, пишем скриншотер

Многие люди считают что php подходит только для разработки сайтиков, и никак не может быть использован, в других областях применения языков программирования, для создания программ… В этой статье я бы хотел осветить, применение php скриптов «не целевым» образом, а именно мы напишем скрипт который будет делать скрин, выгружать его на yandex диск и выводить адрес скриншота в консоль…

Рассмотрим структуру проекта, она очень проста и состоит из 3-х файлов:

1. screen.php — точка входа в приложение.
2. classes/autoload.php — автолоадер проекта.
3. classes/Request.php — класс реализующий запросы к api яндекса.

Далее расмотрим код screen.php:

Как видите это точка входа в приложение, логика проста:
1. Формирование имени скриншота
2. Вызов системной программы scrot
3. Запрос api yandex.disk и выгрузка скриншота

Файл autoload.php тоже очень прост и состоит всего из трёх строк кода, я приведу его лишь для ознакомления, и мы не будем его рассматривать подробно.

Работа с yandex api довольно проста я написал небольшой класс Request.php, с набором неких методов, которые помогают мне в работе с ним…

Рассмотрим ключевые методы данного класса для запроса методов api в основном я использовал file_get_contents, и так как мне приходилось использовать, его при запросе многих методов я написал метод генерации контекста:

Он тоже довольно прост мы создаём контекст с определённом методом запроса и информации об аутентификации…

Далее нам необходимо «создать файл на yandex.disk» это действие мы производим следующим методом:

Как я говорил ранее мы запрашиваем api с помощью функции file_get_contents. После того как этот метод отработает, и вся информация будет запрошена, запускаеться метод upload:

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

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

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

Установка скрипта

Чтож мы закончили, теперь нам предстоит придумать а как же этот скрипт будет работать из консоли? как его запустить там в «глобальной области»? ответом на эти вопросы будет phar — архив содержащий файлы php и способный выполняться как отдельное приложение, похож на тот же jar.

phar мы будем собирать с помощью утилиты box.phar для этого мы пишем простой конфигурационный файл box.json:

Для сборки запускаем:

И наш проект готов теперь осталось только установить права на исполнение файла, и скопировать в директорию /usr/bin/srcphp:

Не забываем о конфигурации файла /home/myname/.config/srcphp/config.php:

в token необходимо вписать полученный oAuth токен от яндекса, при переходе сгенерированной по средством запуска скрипта с ключом —getToken:

Выводы

Главная мысль статьи — рассмотреть как создать консольное приложение с помощью php, на примере программы скриншотера, в следующих я буду поднимать тему использования php в различных сферах применения, и следующая статью будет посвящена разработки простого драйвера usb устройства для linux. Спасибо за внимание и доброго дня.

Источник

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