want to run c program from php using exec() function - php

i'm trying to run one c executable file using php exec().
When c contains a simple program like print hello. I'm using
exec('./print.out')
It's working fine. But when I need to pass a argument to my c program I'm using
exec('./arugment.out -n 1234')
It is not working. Can any body tell me how to pass arugment using exec to c program.

From taking a look at the php documentation, it appears that exec treats arguments a bit oddly. You could try doing
exec("./argument.out '-n 1234'")
to prevent it from mangling them (it normally separates them all on space, which might be what's messing it up).

Related

Python PHP equivalent

I have been using PHP for a while now with my Apache2 web server on my raspberry pi. It works great, but I get tired of always having to think "how do I X in PHP" or "what was the function name for this in PHP".
I am under the strong impression that there should be something equivalent in which I can replace the <?php ?> code with python code, but my search results have been confusing at best.
I am essentially looking for something where I can write whatever python code I want in an HTML script and have it interpreted and executed and its output inserted into the page when it is requested.
For example, to make a table of users from a list in python.
<table><tr><td>User list</td></tr>
<?python
import json
library=json.load(open(some_json_file,'r'));
for user in library:
print "<tr><td>"+user+"</td></tr>"
?>
</table>
I'm under the impression that chameleon can do this with its code blocks as described here,(https://chameleon.readthedocs.io/en/latest/reference.html) but as I look deeper, I get the impression it doesn't work like I am thinking it should. This is the impression I have gotten from all of the template engines I have looked at, as well as WSGI
Are there good drop in python alternatives for PHP? Or are there ways to cleanly wrap semi complex python code into my php in way that doesn't involve writing an additional python script that is called by PHP? I've tried exec() with python -c; but this was less than ideal having to escape all the ' and " characters...
update
The below code works just fine, but can become very slow if run multiple times in a script (takes about 0.4 seconds each time on a raspberry pi3). I have written a program in python that runs in the background and handles requests from php, and runs about 15x faster. I'm now maintaining it here on github.
Original Answer
After messing around I was able to come up with something mostly suitable for what I am trying to do. Inside my php I create a function that executes python scripts.
<?php
function py($s){
exec("python -c '$s'",$arr);
foreach($arr as $v){
echo $v."\n";}
}
?>
Then I use php Heredoc(equivalent to python """ , means I don't have to escape every single double quote) to fill the function:
<?php
py(<<<python
print "Hello world<br>"
s="ello world"
for x in s:
print x+"<br>"
python
);
?>
outputs >>>
Hello world
e
l
l
o
w
o
r
l
d
the only real downside I am experiencing at this point is that this method precludes me from using single quotes anywhere in my python script... :(. I'll get over it.
EDIT
I added a few more tweaks to make this even more useful. The new function is below:
<?php
function py($s,$return=false){
$s=str_replace("'","'\''",$s);
$h=<<<head
def cleanup():
for x in globals().keys():
if not x.startswith("_"):
del globals()[x]
import dill
try:
dill.load_session("pyworking.pkl")
except:
pass
head;
$f=<<<foot
import dill
dill.dump_session("pyworking.pkl")
foot;
if ($return==false){
echo shell_exec("python -c '$h$s$f'");
}
else {
return shell_exec("python -c '$h$s$f'");
}
}
?>
this allows you to use single quotes in the script and invoke the py() function multiple times in the same script and your variables and modules will follow you. At the end of the script you just call the clean up (or using php clear the pyworking.pkl file) and wipe the environment clean.
I also put this function in a file and in my pyp.ini I used the auto_prepend_file=my/file/location to automatically include it, so no need to load it before hand.
Overall I am very happy with this method, especially since I can read php variables inside my python script. Passing objects is as simple as:
<?php
$data_en=json_encode($data);
py(<<<p
import json
data=$data_en
#do something with data
p
);
?>
this would be perfect if I could think of a way to assign values to php variables inside the script, but its not a bad workaround if you want a fusion of php and python or just a way to do everything in python without writing a python webserver (which i have also done).

Passing argument from PHP to Python not working

I have a python srcipt, called rainbow.py. I can run it optionally with an argument. From command line
python rainbow.py, python rainbow.py 4 works well. When I call this script from php I am unable to pass the argument.
I tried:
$argument=4;
exec("python rainbow.py 4");
exec("python rainbow.py $argument");
exec("python rainboy.py .$argument");
They make the code run like there's no valid argument. (I use duration=int(sys.argv[1] in my python code, the script needs to stop after a while, and when calling from php, always the default duration is active)
I tried
$argument="4"
too, did not work.
Can you tell me what's wrong?How can I pass this argument through? I am confident with python, but a total php newbie.
part of my php code:
$argument="2";
echo "printing line <br>";
exec("python rainbow.py $argument");//duration option does not work
part of my python code:
duration=10
try:
if sys.argv[1]!=None:
print "arg found!"
duration=int(sys.argv[1])
except: pass
print "duration:",duration
I cant see the duration printing out when calling python from php, but from LEDs I can cleary see the duration is always 10 seconds
I added sudo to the python call:
exec("sudo python rainbow.py $argument")
and it works now properly. Can someone tell me why?
The python script ran without it too, but without considering the argument.

Pass input to a C program and get output using php

I am working on a project and I wrote two C programs that convert date and time into minutes and then back. What I want to do is pass a php variable into a C program and then have the C program return the result to a variable in php.
I realize that you can use popen or exec commands but I am unsure how to use these commands.
How would I structure the php code?
What input and output commands would I have to use in the C program? If you guys could give me a few examples that would be great. I learn better from examples.
Thanks in advance.
$cmd = "/path/to/prog " . escapeshellarg($something);
$c_output = shell_exec($cmd);

PHP + Python - use PHP to pass string to Python program, and parse output

I have a great Python program on my webserver, which I want to use from inside my PHP web app.
Here's an example of the python command, and output as you would see it in terminal:
>>> print MBSP.parse('I ate pizza with a fork.')
I/PRP/I-NP/O/NP-SBJ-1/O/i
ate/VBD/I-VP/O/VP-1/A1/eat
pizza/NN/I-NP/O/NP-OBJ-1/O/pizza
with/IN/I-PP/B-PNP/O/P1/with
a/DT/I-NP/I-PNP/O/P1/a
fork/NN/I-NP/I-PNP/O/P1/fork ././O/O/O/O/.
You might recognize this as a typical POS tagger.
In any case, I'm confused about how to use a PHP-based web app to send this program a string like "I ate pizza with a fork", and somehow get the response back in a way that can be further parsed in PHP.
The idea is to use PHP to pass this text to the Python program, and then grab the response to be parsed by PHP by selecting certain types of words.
It seems like in PHP the usual suspects are popen() and proc_open(), but popen() is only for sending, or receiving information - not both? Is popen() able to give me access to this output (above) that I'm getting from the Python program? Or is there a better method? What about curl?
Here are all my options in terms of functions in PHP:
http://us.php.net/manual/en/function.proc-open.php
I'm lost on this, so thanks for your wise words of wisdom!
I use exec() for this purpose.
exec($command, $output);
print_r($output);
If you want to get a little heavier / fancier... give your python script an http (or xmlrpc) front end, and call that with a GET/POST. Might not be worth all that machinery though!
You could use popen(), and pass the input to your Python script as a command line argument, then read the output from the file descriptor popen gives you, or proc_open() if you want to interact bi-directionally with the Python script.
Example 1 in the proc_open manual: http://us.php.net/manual/en/function.proc-open.php gives an example of this.
If your Python needs it as stdin, you could try popening a command line:
echo "I ate pizza!"|my_python_progam.py
and just read the output. As usual, do proper input validation before sending it to the command-line.
Something like this would work
$command = '/usr/bin/python2.7 /home/a4337/Desktop/script.py'
$pid = popen('$command',r)
........
........
.........
pclose($pid)

How to use Prolog with PHP?

I want to use Prolog with PHP. Is it possible?
There are always the exec-familiy functions to execute/spawn another process.
As suggested above, you can execute a Prolog interpreter or binary. However, most Prolog implementations also export a C API that can be used to call the Prolog interpreter.
You could create a small PHP module to start an interpreter and execute queries. For instance, the SICStus documentation describes using Prolog from C in detail:
6 Mixing C/C++ and Prolog
Most Prologs allow for prolog code to be compiled into a binary. You could try calling this binary from within PHP using some kind of process call as already mentioned.
I wrote a translator that can convert some simple PHP programs into Prolog and vice-versa.
This is a possible input program:
function is_greater_than($a,$b){
return $a > $b;
}
function is_an_animal($a){
return in_array($a,["dog","cat"]);
}
...and this is the output program:
is_greater_than(A,B) :-
A>B.
is_an_animal(A) :-
member(A,["dog","cat"]).
This translator is only a proof-of-concept, but it may still make it easier to convert some simple PHP programs into Prolog.

Categories