PHP Interactive - Load File From Command Line - php

Is there a way, from a bash script and/or a terminal, to run php interactively and load in a predefined file at the same time?
Essentially, I want to do the following two steps in a single step:
shell# php -a
Interactive mode enabled
php > require_once('ABSOLUTE_PATH_TO_FILE');
I tried using php -a --file='ABSOLUTE_PATH_TO_FILE' but the functions I want to load do not become available in interactive mode.

If you have a test.php file with this contents
<?php
function asd() {
echo "Hi!";
}
?>
You must use:
php -a -d auto_prepend_file=test.php

Related

How i can run function exec in PHP

I can't add * to my code to find file
this code work
exec("mediaconvert -t wav -i /home/20220228/11/23401.rec -o /var/www/html/test.mp3");
if i add a the *, it don't work
exec("mediaconvert -t wav -i /home/20220228/11/*01.rec -o /var/www/html/test.mp3");
p.s. in path is only one file, when i try execute this code from shell it work. Pls help me)
Filename expansion and other bash-specific features may/will not work in other shells (e.g. standard POSIX). If your command with * is not executed in bash/compatible, it won't work as expected. You need to verify the environment/shell that your PHP installation executes commands in.
Run the following test script:
<?php
exec('echo "$SHELL"', $out);
var_dump($out);
When I run the PHP script directly on CLI, I get "/bin/bash" for the shell that's called. When I run it via browser, curiously I get "/sbin/nologin" instead. There are different environments for user apache that executes PHP via browser calls, and the "actual" user logging in via SSH. Bash shell is not available for the Apache user by default.
These results are from a Centos7 server with Apache 2.4/PHP 8.1.4 running. Your mileage may vary. Bottom line: if the command you are executing depends on bash-specific features, it must execute in a bash environment, or another shell that supports the required features.
If bash is not available, your other option is using e.g. glob to get files matching the pattern in your directory, and then loop over them while executing the command for each specific file.
Edit: As pointed out by #Sammitch (see comments), /sbin/nologin is a common "shell name" choice for non-login users, and most likely uses /bin/sh. This should still allow for filename expansion/globbing. Testing browser script call with exec('ls *.php', $out); the wildcard functions as expected.
You may find this question/answer relevant: Use php exec to launch a linux command with brace expansion.
I recommend you do the opposite. First, get the files you want to input then you exec. For instance:
$input_files = ...
exec("mediaconvert -t wav -i " . $input_files . " -o /var/www/html/test.mp3");
You can try to find files with glob() function and after that you can use exec(). You can try a similiar solution with the following code:
$input_files = '/home/20220228/11/*01.rec';
foreach (glob($input_files) as $filename) {
exec("mediaconvert -t wav -i " . $filename . " -o /var/www/html/test.mp3");
}

How do I execute multiple PHP files in single shell line?

I have some PHP files. Each of them start a socket listener, or run an infinite loop. The scripts halt when are executed via php command:
php sock_listener.php ...halt there
php listener2.php ... halt there
...
Currently I use screen command to start all the listener PHP files every time the machine is rebooted. Is there a way I can start all the listener PHP files in single shell line so that I can write a shell script to make it easier to use?
Using screen
Create a detached screen session for the first script:
session='php-test'
screen -S "$session" -d -m -t A php a.php
where -d -m combination causes screen to create a detached session.
Run the rest of the scripts in the same session in separate windows:
screen -S "$session" -X screen -t B php b.php
screen -S "$session" -X screen -t C php c.php
where
-X sends the built-in screen command to the running session;
-t sets the window title.
The session will be available in the output of screen -ls command:
There is a screen on:
8951.php-test (Detached)
Connect to the session using -r option, e.g.:
screen -r 8951.php-test
List the windows within the screen session with Ctrl-a " shortcut, or windowlist -b command.
Forking Processes to Background
A less convenient way is to send the commands to background by appending an ampersand at the end of each command:
nohup php a.php 2>a.php.err >a.php.out &
nohup php b.php 2>b.php.err >b.php.out &
nohup php c.php 2>c.php.err >c.php.out &
where
nohup prevents termination of the commands, if the user logs out of the shell. Read this tutorial for more information;
2>a.php.err redirects the standard error to a.php.err file;
>a.php.out redirects the standard output to a.php.out file.
Is there a way I can start all the listener PHP files in single shell line so that I can write a shell script to make it easier to use?
You can put the above-mentioned commands into a shell script file, e.g.:
#!/bin/bash -
# Put the commands here
make it executable:
chmod +x /path/to/script
and call it when you need it:
/path/to/script
Modify the shebang as appropriate.
Just run them under circus. Circus will let you define a number of processes and how many instances you want to run, and just keep them running.
https://circus.readthedocs.io/en/latest/

Run php script with grunt

I have a php script (lets call this /test.php) on my server. After Grunt automatically has parsed my SCSS and JS I would like to run this test.php script (it resets my memcache). I can't seem to find a way to do this. Anyone got a clue?
You can use grunt-shell to run your php script on cli via php -f your-script.php
grunt.initConfig({
shell: {
php: {
command: 'php -f your-script.php'
}
}
}
grunt.registerTask('runTestPhp', ['shell:php']);
If you don't want to run your php script through cli, have a look at grunt-php.

Initialising PHP interactive

I often find PHP's interactive mode—php -a—very useful, but it would be far more useful if I could start it and have a few commands executed right away to initialize my environment. Things like run the autoloader, set up a few use shortcuts for namespaces, etc.
Here's an example:
include "../../autoloader.php";
use App/Foo/Bar as Bar;
I thought maybe I could just add these lines to a text file initialize.txt and then start the interactive mode with php -a < initialize.txt, but that didn't work.
How can I do this?
As Tomas Creemers mentioned, you have to use auto_prepend_file PHP flag to auto-require a file. For example:
<?php
# foo.php
function bar() { print "Bar.\n"; }
You can load the PHP interpreter like this:
php -d auto_prepend_file=$PWD/foo.php -a
Session:
Interactive shell
php > bar();
Bar.
Or you can include file manually:
php -a
Session:
Interactive shell
php > include 'foo.php';
php > bar();
Bar.
You can use the php.ini setting auto_prepend_file to specify a file that should always be executed before the actual file.
According to the documentation on interactive shell, this setting is also active there.
Assuming you don't want to do this initialization for every single time you start PHP, I would suggest creating a copy of your php.ini file (call it 'php.ini-interactive', for example) and specify that configuration file with the -c option: php -c /path/to/php.ini-interactive -a.
According to a comment (by "Ryan P") on the documentation page for PHP interactive shell, php -a does not always do the same thing:
Interactive Shell and Interactive Mode are not the same thing, despite
the similar names and functionality.
If you type 'php -a' and get a response of 'Interactive Shell'
followed by a 'php>' prompt, you have interactive shell available (PHP
was compiled with readline support). If instead you get a response of
'Interactive mode enabled', you DO NOT have interactive shell
available and this article does not apply to you.
You can also check 'php -m' and see if readline is listed in the
output - if not, you don't have interactive shell.
Interactive mode is essentially like running php with stdin as the
file input. You just type code, and when you're done (Ctrl-D), php
executes whatever you typed as if it were a normal PHP (PHTML) file -
hence you start in interactive mode with '<?php' in order to execute
code.
I do not have a copy of PHP with interactive shell available. I only have interactive mode, apparently. I have tested (see below) and can confirm that files configured with auto_prepend_file are executed in interactive mode. However, you may want to reconsider using it if you get the same symptoms as me:
cat /tmp/prepend.php
Output:
<?php
echo 'cookies are people too!';
Further:
grep auto_prepend_file /etc/php5/cli/php.ini
Output:
auto_prepend_file =
grep auto_prepend_file /etc/php5/cli/php.ini-interactive
Output:
auto_prepend_file = /tmp/prepend.php
php -a
Session:
Interactive mode enabled
php -c /etc/php5/cli/php.ini-interactive -a
Output:
Interactive mode enabled
cookies are people too!
Segmentation fault
php --version
Output:
PHP 5.4.4-14+deb7u2 (cli) (built: Jun 5 2013 07:56:44)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies
(Keyboard input in that last interactive mode run is only a return followed by Ctrl + D.)

Running php script (php function) in linux bash

How we run php script using Linux bash?
php file test.php
test.php contains:
<?php echo "hello\n" ?>
From the command line, enter this:
php -f filename.php
Make sure that filename.php both includes and executes the function you want to test. Anything you echo out will appear in the console, including errors.
Be wary that often the php.ini for Apache PHP is different from CLI PHP (command line interface).
Reference: https://secure.php.net/manual/en/features.commandline.usage.php
First of all check to see if your PHP installation supports CLI. Type: php -v. You can execute PHP from the command line in 2 ways:
php yourfile.php
php -r 'print("Hello world");'
There are two ways you can do this. One is the one already mentioned, i.e.:
php -f filename.php
The second option is making the script executable (chmod +x filename.php) and adding the following line to the top of your .php file:
#!/path/to/php
I'm not sure though if a webserver likes this, so if you also want to use the .php file in a website, that might not be the best idea. Still, if you're just writing some kind of script, it is easier to type ./path/to/phpfile.php than having to type php -f /path/to/phpfile.php every time.
Simply this should do:
php test.php
just run in linux terminal to get phpinfo .
php -r 'phpinfo();'
and to run file like index.php
php -f index.php
php -f test.php
See the manual for full details of running PHP from the command line
php test.php
should do it, or
php -f test.php
to be explicit.
I was in need to decode URL in a Bash script. So I decide to use PHP in this way:
$ cat url-decode.sh
#!/bin/bash
URL='url=https%3a%2f%2f1%2fecp%2f'
/usr/bin/php -r '$arg1 = $argv[1];echo rawurldecode($arg1);' "$URL"
Sample output:
$ ./url-decode.sh
url=https://1/ecp/

Categories