How to take user input from HTML form to C program - php

I have this small program which takes input from stdin
sample.c
#include<stdio.h>
main()
{
int l=0;
scanf("%d",&l);
printf("\n%d",l);
}
ofcourse! compiled it: cc sample.c and got a.out
and i am trying to run it via php like
$runcmd = "./a.out > output.txt";
exec($runcmd,$outp);
print_r($outp);
my problem is i dont have any idea how to give input to this program so that scanf can read that?
please help me here!
googling gave some tips like proc_open, popen .... but i couldn't make it.
Thanks in Advance.

take a look at popen
http://se1.php.net/popen
it works a bit like fopen, and when using fwrite, insted of writing to a file you can write to a prosses stdin insted.
$runcmd = "./a.out > output.txt";
$process_stdin = popen($runcmd, 'w');
fwrite($process_stdin, "text to send to process");
pclose($process_stdin);

If you design your C program as a server, you should use sockets or named pipe. That way, you will be able to interact with it without launching it.
You can use popen if you want to use it multiple time almong your script.
If you just need to use it one time, you can just pass parameter as arguments.

Why not passing it as a command line argument to your C program. Then instead of using scanf you get your input in argv[].

Related

How can I send "user input" to python script from another python script (or php execute)?

I'm creating a website using php and XAMPP. This website accepts a python file from the user, then it needs to run that python file and receive all output from that file. I've been able to accomplish this by using shell_exec() in the php file.
The problem is getting user input for the python files. The files use both the input() and sys.stdin.readline() functions. I need to be able to automatically send the python file "user input" (sometimes several inputs). I know exactly what and how many "user inputs" I will need to send so this doesn't require my intervention.
I think one way to do this is by changing the way the submitted python files get input. If I could do this then I would have each input stored in a list that would be iterated through. Unfortunately, I cannot edit the actual input commands in the submitted files so this would have to be done at the top of the submitted python file.
Here is how the php file executes the python files.
$command = "python python_script.py";
$output = shell_exec($command);
echo nl2br($output);
I tried using the echo function (with the && for multiple inputs), but the only problem with this is the fact that the echo function can't press enter after each echo. This did however successfully match the inputs to the input prompts. Below is an example.
python_script.py should take input then print it, but the cmd displayed this:
C:\>(echo 2 && echo 3) | python python_script.py
number one: 2
number two: 3
C:\>
Now I'm trying to use the subprocess functions in a separate python file. Again the problem is "user input"; I don't know how to send inputs. The solutions to like problems have not been able to work for me, but I'm certain that this is due to my lack of understanding of the subprocess functions.
I think that subprocess is my best bet, but I would also appreciate any suggestions utilizing php. I would also prefer to not have to create a batch file for this problem.
I found a solution to this problem.
To send inputs from one python file to another (python version 3.7), I used three files.
File for running the subprocess
File for outputs (very simple)
File that needs the inputs
Here are the three files in the same order as above.
You don't need to print out the output, but I'll include the terminal output below the file examples.
The subprocess file:
from subprocess import Popen,PIPE
p1 = Popen(["python","output_file.py"], stdout=PIPE)
p2 = Popen(["python", "input_file.py"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()
output = p2.communicate()[0]
print(output)
The output file is very simple and there may be a way to work around it. Nevertheless, here is my version:
print(1)
print(2)
print('My String')
The input file requires type casting for numbers.
i = input('Enter a number: ')
j = input('Enter another: ')
k = int(i) + int(j)
print(k)
l = input('Tell me something. ')
print(l)
Here is the terminal output:
b'Enter a number: Enter another: 3\r\nTell me something. My String!\r\n'

PHP excute Python SFTP script

in PHP I need to do some SFTP, but I am having issues because I am not allowed to install the SSH extension, and phpseclib is not working how I need it to.
As such, I am going to execute a Python script to do the SFTP for me. What I imaging is doing something like the following
exec("SFTPUpload.py remoteFile serverLocation");
So I execute SFTPUpload.py passing it the location of the file on my server which needs transferring, and the location on the server it needs transferring too.
In terms of the Python script (I am not too familiar with Python), I imagine it would be something like the following
username='sftpUser'
password='sftpPassword'
port=22
#SFTP
client.load_system_host_keys()
print " hostname =%s \n username=%s \n password=%s \n" (hostname,username,password)
t = paramiko.Transport((hostname, port))
t.connect(username=username,password=password)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put(source,destination)
sftp.close()
t.close()
However, the way I am calling it from PHP, I need the Python to be in a class or something so I can pass it the variables.
How would I achieve something like this?
Thanks
I believe you can do it with the exec() function as you described by simply parsing the command line parameters in Python.
Like:
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
Where you can access the elements in sys.argv like a list.
(You could also take a look at the getopt module which offers even more (C-like) parameter passing options, but I believe the above solution will do.)
If the exec() function does not work, I believe you could consider to use the system function in PHP:
Something like this:
$mystring = system('SFTPUpload.py remoteFile serverLocation', $retval);

Trouble with Named Pipes

I am new to using php and python but I have a task that I am trying to complete and the test code I have does not seem to work. Basically I am trying to get data from an html form (using php) to a python script for processing. After looking at some really useful stuff from other posts I have decided to use pipes. To test the process I have used the following code.
php code:
<?php
$pipe = fopen('Testpipe','r+');
fwrite($pipe, 'Test');
fclose($pipe);
?>
Python code:
#!/usr/bin/env python
import os
pipeName = 'Testpipe'
try:
os.unlink(pipeName)
except:
pass
os.mkfifo(pipeName)
pipe = open(pipeName, 'r')
while True:
data = pipe.readline()
if data != '':
print repr(data)
When I run the Python code I can see the pipe being created in the directory using ls -l but when I use my browser to run the php script (I am running a webserver on a raspberry pi) nothing happens. It has got me a little confused as most of the posts I read state how simple pipes are to get going. I assume on opening the browser (php script through the server) I should see the text come up in the python shell?
Any help would be appreciated.
Ok further to my original post I have modified my original code thanks to alot of trawling through the net and some really useful Python tutorials. I now have something that proves the principal of pipes although I still have to resolve the php side of things but I feel as though I'm getting there now. Revised code is below:
import os,sys
pipe_name = 'testpipe'
def child():
pipeout = os.open(pipe_name, os.O_WRONLY)
while True:
time.sleep(1)
os.write(pipeout, 'Test\n')
def parent():
pipein = open(pipe_name, 'r')
while True:
line = pipein.readline()[:-1]
print 'Parent %d got "%s"' %(os.getpid(),line)
if not os.path.exists(pipe_name):
os.mkfifo(pipe_name)
pid = os.fork()
if pid != 0:
parent()
else:
child()
This has got me on the path to where I want to go so hopefully it may be of use to someone having similar questions.
try to provide an absolute path ("/tmp/TestPipe") to be sure that both are looking to the same file.

Executing a php script from C

I am trying to write a c program that executes a PHP script.
I tried using php_execute_script function that I came across in my google search.
However, it seems I have to call TSRMLS_FETCH() which throws an exception.
Does anyone have an idea why? or how should I do this in the proper way?
Thanks.
you can use exec function:
exec ("php myscript.php");
or you can use popen:
FILE *p;
p = popen("php myscript.php","r");
pclose(p);
What you want is embedding the PHP interpreter.
You may try PHPEmbed from the facebook github

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