Running script and executing PHP for output - php

I'm looking to run a program, and for every output line it generates, execute a PHP script and pass the line content to it.
I know, pretty hard to understand. Here's an example:
Execute script -> script outputs 'Initializing script on 127.0.0.1'. Now it needs to execute a command like php5 input.php 'Initializing script on 127.0.0.1'.
Is this doable? If so, how would I go about doing this?
Edit: to clarify; I basically want command > log.txt but in stead of writing the output to that file, writing it to a PHP script as an argument

PHP is an interpreter much like Bash, Python, etc, so you can do "normal" scripting with it. For example:
#!/usr/bin/php5
<?php
echo "Hello, world!\n";
while($line = fgets(STDIN)) {
echo "> " . $line;
}
?>
Mark the file as executable, then run:
$ /program/that/generates/lines | /path/to/your/php/script
However, contrary to your original question, it sounds to me like you actually want to use JavaScript and possibly AJAX for web purposes. Sane web applications will have the said script run in the background and safely write the results to a file or stream, using AJAX to read it and update the information on the current page.

Related

php echo to elixir iex stdin

ok, I know I'm doing something weird here but I gotta do it.
So my elixir program needs to run one PHP script and take the information from that script, but it never comes in. I can manually run the php script and it works fine. At the bottom of the script it says:
echo $avar->getPUId();
So it's printing it out to echo I guess. I get the data I need when I run it from a command line:
C:\PHP>php.exe "-f" "C:\pap.php" "613b8859"
37a69912
But when I run it from iex I get nothing:
iex(1)> System.cmd("C:\\PHP\\php.exe", ["-f", "C:\\pap.php", "613b8859"])
Terminate batch job (Y/N)? y
Now, if I mess up on the filename or something php will give me an error in response saying like:
iex(1)> System.cmd("C:\\PHP\\php.exe", ["-f", "C:\\pap321.php", "613b8859"])
{"Could not open input file: c:/pap123.php\n", 1}
...
so I know I can talk to PHP, and it can talk back to me with errors, but echo isn't caught by my elixir application that calls it apparently. Is there any other way I can grab the data as it comes out of the PHP script?
I used
https://github.com/alco/porcelain
result = Porcelain.shell("C:\\PHP\\php.exe -f C:\\pap.php 613b8859")
IO.inspect result.out
it worked great.

Live output of shell script using `watch` in browser?

I've seen PHP reading shell_exec live output and PHP: Outputting the system / Shell_exec command output in web browser, but can't get the following working.
NB: originally, my shell script was running some python, but I have simplified it.
live.sh
uname -a
date
watch --no-title date
live.php
<?php
$cmd = "sh live.sh";
while (# ob_end_flush()); // end all output buffers if any
$proc = popen($cmd, 'r');
echo '<pre>';
while (!feof($proc))
{
echo fread($proc, 4096);
# flush();
}
echo '</pre>';
?>
The uname and date outputs appear in the browser okay, but the watch output does not.
Am I in fact attempting the impossible?
I would advise against the approach of using watch, and you are probably in for more trouble than you expect.
Firstly, long running command might be affected by the (default) PHP timeout, so you may have to tweak that.
Then, watch probably uses terminal sequences to clear the screen, and I am not sure how this translates to the output code.
I would rather suggest setting up a client side mechanism to periodically repeat a call to the sever side live.php.
This post on SO will help you get started.
jQuery, simple polling example
the page above uses the jquery library, but you could use native Javascript equivalent if you want to.
The simplest example (from that page) would be :
function poll(){
$("live.php", function(data){
$("#output_container").html(data);
});
}
setInterval(function(){ poll(); }, 5000);
In your page, set up a container for your results
<div id="output_container"></div>
In your example, you remove the watch from your script and replace it with the command you intended watching.
You probably want this only for some special thing. So, for those you can try ajaxterm.
Really easy to use, (4.line installation)
wget http://antony.lesuisse.org/software/ajaxterm/files/Ajaxterm-0.10.tar.gz
tar zxvf Ajaxterm-0.10.tar.gz
cd Ajaxterm-0.10
./ajaxterm.py
and you will get full bash running interactively in the browser. (after the login/password). Written in python, so easily adaptible for you. Also, see here.

Calling Perl script with PHP, passing variables and put result into a file

I am near losing my mind cause of a perl script I want to call via PHP.
I have a PHP Form where I put in a MySQL Query which gets stored in a file and choosing some variables.
If I call any SHELL command like "top" ... everything works fine, but as soon as I try to call my perl script with variables, there are no results at all.
The file where the results should get stored stays empty.
That's the calling part from the PHP File:
if (isset($_POST['submit'])) {
$file = 'query.sql';
$query = $_POST['query'];
file_put_contents($file, $query);
$command = "perl /home/www/host/html/cgi/remote-board-exec.pl -sqlfileexec query.sql > /home/www/host/html/cgi/passthrutest.txt";
exec($command, &$ausgabe, $return_var);
There is no error message and i already tried debug things, but nothing helped :(
Are you sure that perl is being executed? Perhaps you ought to replace the command with 'which perl' just to make sure, and to use the full path to Perl. Another idea is to make sure your:
perl script is executable (use chmod)
ensure it has '#!/usr/bin/perl' (or wherever your path to perl is)
change the command to "/home/www/host/cgi/remote-board-exec.pl..." without the perl command
dump the contents of your output array ($ausgabe) as if the command fails to execute you may find out what is happening.

issuing things to shell and forgetting about it in php

how do you issue commands to the shell and then forget it's output and such? for example:
<?php
echo `sleep 2;echo hi`;
echo "foo";
?>
the result for this is hifoo. i would want a result that gives me foohi. why? i want the command issued to the shell simply issued and forgotten, i am confused about why PHP will wait for the result. is such a result possible?
(the idea behind this is setting up the correct number of selenium grid RC instances programatically. currently, it will stop after the first process is opened)
From php.net exec()
If a program is started with this
function, in order for it to continue
running in the background, the output
of the program must be redirected to a
file or another output stream. Failing
to do so will cause PHP to hang until
the execution of the program ends.
The same applies for all shell commands.
It's like anything you do at the command prompt, unless you take measures to put the new command in the background, the shell (and PHP ) will block until the command exits. Try this:
<?php
echo `(sleep 2; echo hi) &`;
echo 'foo';
?>
Note the brackets around your command, without that, the & woulud apply only to the echo , and you'd still have the 2 second pause.

Calling Python in PHP

I have a Python script I recently wrote that I call using the command line with some options. I now want a very thin web interface to call this script locally on my Mac.
I don't want to go through the minor trouble of installing mod_python or mod_wsgi on my Mac, so I was just going to do a system() or popen() from PHP to call the Python script.
Any better ideas?
Depending on what you are doing, system() or popen() may be perfect. Use system() if the Python script has no output, or if you want the Python script's output to go directly to the browser. Use popen() if you want to write data to the Python script's standard input, or read data from the Python script's standard output in php. popen() will only let you read or write, but not both. If you want both, check out proc_open(), but with two way communication between programs you need to be careful to avoid deadlocks, where each program is waiting for the other to do something.
If you want to pass user supplied data to the Python script, then the big thing to be careful about is command injection. If you aren't careful, your user could send you data like "; evilcommand ;" and make your program execute arbitrary commands against your will.
escapeshellarg() and escapeshellcmd() can help with this, but personally I like to remove everything that isn't a known good character, using something like
preg_replace('/[^a-zA-Z0-9]/', '', $str)
The shell_exec() operator will also allow you to run python scripts using similar syntax to above
In a python file called python.py:
hello = "hello"
world = "world"
print hello + " " + world
In a php file called python.php:
$python = shell_exec(python python.py);
echo $python;
You can run a python script via php, and outputs on browser.
Basically you have to call the python script this way:
$command = "python /path/to/python_script.py 2>&1";
$pid = popen( $command,"r");
while( !feof( $pid ) )
{
echo fread($pid, 256);
flush();
ob_flush();
usleep(100000);
}
pclose($pid);
Note: if you run any time.sleep() in you python code, it will not outputs the results on browser.
For full codes working, visit How to execute python script from php and show output on browser
I do this kind of thing all the time for quick-and-dirty scripts. It's quite common to have a CGI or PHP script that just uses system/popen to call some external program.
Just be extra careful if your web server is open to the internet at large. Be sure to sanitize your GET/POST input in this case so as to not allow attackers to run arbitrary commands on your machine.
Your call_python_file.php should look like this:
<?php
$item='Everything is awesome!!';
$tmp = exec("py.py $item");
echo $tmp;
?>
This executes the python script and outputs the result to the browser.
While in your python script the (sys.argv[1:]) variable will bring in all your arguments. To display the argv as a string for wherever your php is pulling from so if you want to do a text area:
import sys
list1 = ' '.join(sys.argv[1:])
def main():
print list1
if __name__ == '__main__':
main()
The above methods seems to be complex. Use my method as a reference.
I have this two files
run.php
mkdir.py
Here, I've created a html page which contains GO button. Whenever you press this button a new folder will be created in directory whose path you have mentioned.
run.php
<html>
<body>
<head>
<title>
run
</title>
</head>
<form method="post">
<input type="submit" value="GO" name="GO">
</form>
</body>
</html>
<?php
if(isset($_POST['GO']))
{
shell_exec("python /var/www/html/lab/mkdir.py");
echo"success";
}
?>
mkdir.py
#!/usr/bin/env python
import os
os.makedirs("thisfolder");
Note that if you are using a virtual environment (as in shared hosting) then you must adjust your path to python, e.g: /home/user/mypython/bin/python ./cgi-bin/test.py
is so easy 😁
You can use [phpy - library for php][1]
php file
<?php
require_once "vendor/autoload.php";
use app\core\App;
$app = new App();
$python = $app->python;
$output = $python->set(your python path)->send(data..)->gen();
var_dump($ouput);
python file:
import include.library.phpy as phpy
print(phpy.get_data(number of data , first = 1 , two =2 ...))
you can see also example in github page
[1]: https://github.com/Raeen123/phpy
If you want to execute your Python script in PHP, it's necessary to do this command in your php script:
exec('your script python.py')

Categories