Open Vim From PHP CLI - php

How do you open up vim from a CLI like svn and git do when you drop -m from commit commands?
I'm getting the follow error: Vim: Warning: Output is not to a terminal
`echo "Please edit this file" > file.name`;
`vim file.name`;

PHP Doesn't automatically pass thru the STDIN/STDOUT streams, you need to do it manually:
`echo "Please edit this file" > file.name`;
system("vim file.name > `tty`");
(Note: I don't really understand what I'm talking about, I just know the above works.)

Hi this is a example using proc_open in PHP, only runs in systems with /dev/tty (Linux/OSX)
<?php
$descriptors = array(
array('file', '/dev/tty', 'r'),
array('file', '/dev/tty', 'w'),
array('file', '/dev/tty', 'w')
);
$process = proc_open('vim', $descriptors, $pipes);

EDIT:
I just realized it sounds like you already have this set up for svn/git... what are you trying to open it from?
for bash: export SVN_EDITOR=vim although EDITOR will work as well, though this will influence other things as well. IF for some reason vim isnt on your path youll need to use the full path as well. Place this in your .profile or .bash_profile.

Related

unable to execute python script from php

I want to execute Python script from PHP file. I am able to execute simple python script like:
print("Hello World")
but when I want to execute following script, nothing happens
from pydub import AudioSegment
AudioSegment.converter = "/usr/bin/ffmpeg"
sound = AudioSegment.from_file("/var/www/dev.com/public_html/track.mp3")
sound.export("/var/www/dev.com/public_html/test.mp3", format="mp3", bitrate="96k")
and same script works fine when I execute it from terminal. here is my php script:
$output = shell_exec("/usr/bin/python /var/www/dev.com/public_html/index.py");
echo $output;
I have also tried following method but no luck:
$output = array();
$output = passthru("/usr/bin/python /var/www/dev.com/public_html/index.py");
print_r($output);
please help me
PHP's passthru function does not have the elegant method for which you may be searching of passing environment variables. If you must use passthru, then export your variables directly in the command:
passthru("SOMEVAR=$yourVar PATH=$newPATH ... /path/to/executable $arg1 $arg2 ...")
If you are inclined toward shell_exec, you may appreciate putenv for the slightly cleaner interface:
putenv("SOMEVAR=$yourVar");
putenv("PATH=$newPATH");
echo shell_exec("/path/to/executable $arg1 $arg2 ...");
If you are open to a more robust (if tedious) approach, consider proc_open:
$cmd = "/path/to/executable arg1 arg2 ..."
# Files 0, 1, 2 are the standard "stdin", "stdout", and "stderr"; For details
# read the PHP docs on proc_open. The key here is to give the child process a
# pipe to write to, and from which we will read and handle the "passthru"
# ourselves
$fileDescriptors = array(
0 => ["pipe", "r"],
1 => ["pipe", "w"],
2 => ["pipe", "w"]
);
$cwd = '/tmp';
$env = [
'PATH' => $newPATH,
'SOMEVAR' => $someVar,
...
];
# "pHandle" = "Process handle". Note that $pipes is new here, and will be
# given back to us
$pHandle = proc_open($cmd, $fileDescriptors, $pipes, $cwd, $env);
# crucial: did proc_open work?
if ( is_resource( $pHandle ) ) {
# $pipes is now valid
$pstdout = $pipes[ 1 ];
# Hey, whaddya know? PHP has just what we need...
fpassthru( $pstdout );
# Whenever you proc_open, you must also proc_close. Just don't
# forget to close any open file handles
fclose( $pipes[0] );
fclose( $pipes[1] );
fclose( $pipes[2] );
proc_close( $pHandle );
}
Acc to your reply, as you want to execute the python script from PHP
I was able to execute it using the following code
$command = escapeshellcmd('/var/www/yourscript.py');
$output = shell_exec($command);
echo $output;
Please use the above PHP code with the same python script.
Try to run the python script as a GCI script first to make sure it is working and set the permissions to public directory and script as I mentioned before
===================old ans============================
From what you asked, I guess this is what you are trying to do is that you are trying to run it as a CGI script like http://localhost/yourscript.py
And why are you using PHP to execute python script when you can run it directly as a CGI script?
here is what you need to do to make it work like a web page:
enable python CGI in apache ( or in the web server you are using ).
put the script in CGI configured directory
add proper code to your script to make it work as a CGI script
#!/usr/local/bin/python
from pydub import AudioSegment
AudioSegment.converter = "/usr/local/bin/ffmpeg"
sound = AudioSegment.from_file("/var/www/dev.com/public_html/track.mp3")
sound.export("/var/www/dev.com/public_html/test.mp3", format="mp3", bitrate="96k")
print "Content-type: text/html"
print
print ""
print ""
print ""
print "Done/ you can perform some conditions and print useful info here"
print ""
Give permissions to the script and make the public directory writable
Access the script http://localhost/your-path-to-script.py
I was able to run this properly.
let me know if that's not your case if you want something else
In my case, I did this code.
<?php
chdir('/home/pythontest') ; // python code dir
$commandline="/usr/bin/python3 test.py parameter" ;
exec($commandline, $output, $error) ;
echo $output ;
?>
If you need to set some environments for python, add environment vars like this.
$commmandline="LANG=en_US.utf8 LC_ALL=en_US.utf8 /usr/bin/python3 ..." ;
and check the httpd log.
Check this:
The apache user has to be in sudoers file, better you don't give sudo to apache instead give apache (www-data) user right to run your python program
put first line in your python script: #!/usr/bin/env python so the script knows which program to open it with..
then,
change group:
chgrp www-data /path/to/python-script.py
make it executabe:
chmod +x /path/to/python-script.py
then try it:
shell_exec("/path/to/python-script.py");
I hope this will work! :)
You can also exec ffmpeg directly without python:
$output = shell_exec("/usr/bin/ffmpeg -i in.mp3 -b:a 96k out.mp3");
echo $output;
ffmpeg docs
Answered in 2022.
In php 8.0 and above the following method worked. Above answers are very useful but i am compiling few extra steps here.
PHP Code.
$output = shell_exec("python3 /var/www/python/test.py");
print_r($output);
exec('python3 --version 2>&1', $output);
var_dump($output);
Trying both shell_exe and exec
Make sure the python file has executable permission and added to www-data group (if its ubuntu/debian systems) . sudo chmod +x test.py and sudo chgrp www-data test.py
Make sure the php.ini has disabled_functions line commented or empty.
sudo vim sudo vim /etc/php/8.0/cli/php.ini
sudo vim sudo vim /etc/php/8.0/apache2/php.ini
For both.
I compiled a simple video to make sure others dont spend more time figuring out the problem. https://youtu.be/t-f6b71jyoM

PHP script only executing from command line when command is run from script's directory

I am trying to run this script from the command line:
#!/usr/local/bin/php
<?php
$myfile = fopen("cc.log", "a") or die("Unable to open file!");
$txt = "Success \n";
fwrite($myfile, $txt);
fclose($myfile);
?>
And it works, but only when I cd into the directory of the script and run:
/usr/local/bin/php test_script.php
This also works:
/usr/local/bin/php /home/<username>/public_html/test_script.php
but not when I leave the directory.
Solved by changing line 3 of test_script.php from:
$myfile = fopen("cc.log", "a") or die("Unable to open file!");
to an absolute path:
$myfile = fopen("/home/<username>/public_html/cc.log", "a") or die("Unable to open file!");
The original script created a cc.log file in the directory from where the command was called and appended about 50 "Success" messages xD
A more formal answer to the original question:
Your file (test_script.php) needs to be made executable to be able to be run from anywhere. This can be done with chmod:
chmod 755 test_script.php
and results in the file being able to be run by invoking.
./test_script.php
And now, drumroll please, you should be able to run the file by invoking it like this:
./path/to/test_script.php
That dot at the front of the path should allow you to run the script as an executable without doing anything else.
Hope it helps/works!
(If it doesn't work comment and I'll boot up my Linux machine and try to replicate it!)
EDIT
Ok, that's weird that it doesn't work! Shoot! Is the PHP CLI (command line interface) installed on your Linux server? If so I would encourage you to try:
php /path/to/your/test_script.php
Hope that second suggestion helps!
EDIT 2
Aha moment number 2!!
I believe your php should be installed here: /usr/bin/php, having it in the local folder will not allow you to properly invoke it from another directory!
To download yourself a new installation of php, run
sudo apt-get install php5 libapache2-mod-php5
You will also have to change your script header to #!/usr/bin/php.
This was a good source for this third edit! I really hope it helps!

PHP proc_open() pipes communication

The context is the following:
I'm using a Raspberry Pi with PHP5 and Apache installed on it and it's connected to a LED display.
There are a few executables on the Pi to make this LED display works.
I want my php script to fetch datas from the web with some APIs and display the result on the LED.
So, the display works fine. I have installed a C-based program in the the /var/www/ and here is an example
on /var/www/: sudo ./text-example -f fonts/5x8.bdf -r 16
(-f for the font used, -r for the number of rows of my LED)
When you execute this, you can write some text in the shell and it will display it on the LED.
So I made a simple test.php script with the following: $res = shell_exec('sudo ./test-example -f fonts/5x8.bdf -r 16'); and it works too. I can enter messages in the STDIN.
A little further, now I need to enter the text dynamically so I did a proc_open() in a proc.php:
<?php
$desc = array(0=>array("pipe", "r"), 1=>array("pipe", "w"));
$cwd = '/var/www/';
$process = proc_open('php test.php', $desc, $pipes, $cwd, NULL);
if (is_resource($process)) {
fwrite($pipes[0], 'hello');
fclose($pipes[0]);
}
?>
So, now I run in the shell: php proc.php. As soon as I define a $desc with pipe, the programm will execute, and then stop. The LED display is not displaying anything. If I remove the $desc variable and remove the pipes things (fwrite, fclose), I can enter text in the shell and it will execute properly as if it was test.php. I don't understand why it won't let me STDIN with fwrite and why the php is interrupted with theses pipes.

Open vim from PHP like git

How do i open vim from a PHP file to edit some other file like git when you run "git commit" without the -m flag?
I've tried this solution Open Vim From PHP CLI
from-php-cli but it gets me some IO error with vim :
Vim: Warning: Output is not to a terminal
Vim: Warning: Input is not from a termin?
is there other way to do this? probably with bash or something else?
Vim is an interactive editor. The error you are getting ("Output is not to a terminal") is a precise description of the problem. You can't control Vim from a PHP script.
If you need to pass text, you should use alternative approaches like the aforementioned -m flag or STDIN.
I was able to do it using the proc_open method with one of the solutions from Open Vim From PHP CLI and a cycle that constantly checks if the process is still running. Once you finish editing it continues running the script.
$descriptors = array(
array('file', '/dev/tty', 'r'),
array('file', '/dev/tty', 'w'),
array('file', '/dev/tty', 'w')
);
$process = proc_open($_SERVER['EDITOR']. $filename, $descriptors, $pipes);
//if(is_resource($process))
while(true){
if (proc_get_status($process)['running']==FALSE){
break;
}
}
It's not very elegant but it does the job :)
PS:I'm sorry for the bad English >.<
So you want to execute a bash script with PHP?
Take a look at:
shell_exec()
exec()
http://php.net/manual/de/function.shell-exec.php
http://php.net/manual/de/function.exec.php
The first one will return data from executed command, if you do a cat file.txt you will end up with a string which contains the content of file.txt
If you use exec it will not return std output, but will return true/false if the given command was successful.
You can now write a simple bash script which does manipulate text and then execute it via PHP.

Inject input into process connected to standard input (interactive console)

We have a tool which executes the PHP interactive shell like this:
$descriptorSpec = array(
0 => STDIN,
1 => STDOUT,
2 => STDERR
);
$prependFile = __DIR__ . '/../../../../../res/dev/console_auto_prepend.php';
$exec = 'php -a -d auto_prepend_file=' . escapeshellarg($prependFile);
$pipes = array();
proc_open($exec, $descriptorSpec, $pipes);
The trick with auto_prepend_file unfortunately causes issues with autoloading on PHP 5.3. We found out that everyting works well when we include the file inside the interactive shell:
$ php -a
Interactive shell
php > include "myproject/res/dev/console_auto_prepend.php";
Autoloader initialized.
What we want to do is the following:
execute php interactive shell via proc_open
send the include line to the interactive shell
hand over the controll to the user input
Is there any way to do this?
Untested idea:
Created a new input pipe
Open the PHP process (php -a) with that input pipe, stdout and stderr could be connected to the system pipes
Inject the include command (write to the input pipe)
In a loop read from the STDIN and write to our new input pipe (which is connected to the php -a)
The project ended up in using a custom PHP shell (psysh)

Categories