I'm trying to run a C program of adding two numbers with PHP in a web browser. But when I run the command
exec"gcc name.c -o a & a" it
returns some garbage result like sum is : 8000542.00. It doesn't ask for any input.
I want to give inputs to scanf from the browser. Please suggest to me how can I resolve my problem.
I have tried this but couldn't handle it successfully.
$desc = array(0=> array ('pipe','w'), 1=> array ('pipe','r'));
$cmd = "C:\xampp\htdocs\add.exe";
$pipes=array();
$p = proc_open($cmd,$desc,$pipes);
if(is_resource($p))
{
echo stream_get_contents($pipes[0]);
fclose($pipes[0]);
$return_value=proc_close($p);
echo $return_value;
Related
If I execute an R program through macOS Terminal it works fine, but if I execute that program through PHP exec() I get an error which says "Rscript not found".
submit.php:
<?php
// print "hello";
$a = $_POST['a'];
$b = $_POST['b'];
// echo shell_exec("calc");
$output = exec("Rscript /xampp/htdocs/demo/1.R ".$a." ".$b);
print $output
?>
1.R:
setwd("C:/xampp/htdocs/demo")
print("hello")
args=commandArgs(trailingOnly = TRUE)
a = args[1]
b = args[2]
c = as.numeric(a)+as.numeric(b)
cat(c)
You need to tell the command interpreter where Rscript is located. In a normal login, you'd have a long PATH variable to search through, but when running from PHP you have a much more limited path. To figure out where the executable is located, type which Rscript from Terminal. Use the resulting path in your PHP script.
Also note that dumping raw user input into shell commands is a very bad idea. You should always use escapeshellarg() to make sure the input is sanitized. I would also suggest capturing the full output in the event that R outputs more than one line.
<?php
$a = escapeshellarg($_POST["a"]);
$b = escapeshellarg($_POST["b"]);
$r = "/xampp/htdocs/demo/1.R";
$lastline = exec("/usr/local/bin/Rscript $r $a $b", $output, $return);
// you could check the value of $return for non-zero values as well
// full output is returned as an array
echo implode("\n", $output);
Finally, you'll want to check your setwd() command in the R script. Might have some trouble with C: on a Mac! ;)
I am trying to write a php code that takes coefficients from a html form, sends them to a python algorithm that returns a json object. That object is a list of player names, basically {"Ji" : "Firstname Lastname"} for i from 1 to 15.
The python code (interface.py) I have to create this json is :
import json
i=0
for joueur in best_team:
i+=1
output["J%s"%(i)]=joueur['nom']
out=json.dumps(output)
print(out)
best_team is a list of player dictionnaries with data on them. My player names don't involve any non ASCII characters or whatever.
My php code is the following :
$command = "python interface.py";
$command .= " $coeff1 $coeff2 $coeff3 $coeff4 $coeff5 $coeff6 $coeff7 $coeff8 $coeff9 $coeff10 2>&1";
$pid = popen( $command,"r");
while( !feof( $pid ) )
{
$data = fread($pid, 256);
$data= json_decode($data) ;
echo $data->J1;
flush();
ob_flush();
echo "<script>window.scrollTo(0,99999);</script>";
usleep(100000);
}
pclose($pid);
I call the coefficients from the html and then send back the results via a js file.
But I just get the following error : Notice: Trying to get property of non-object.
Nothing wrong with the js file because if I try instead :
$string = '{"foo": "bar", "cool": "attributlong"}';
$result = json_decode($string);
echo $result ->cool;
It works.
Also if I have instead in my python file :
out={"foo":"bar","word":"longerthaneightcharacters"}
out=json.dumps(out)
print(out)
It works as well (replacing J1 by word in php code of course).
And funny enough, if i have in python:
output={}
i=0
for joueur in best_team:
i+=1
output["J%s"%(i)]="short"
output["J%s"%(i)]=str(output["J%s"%(i)])
out=json.dumps(output)
print(out)
It works, and if I replace "short" by "longerthaneightcharacters" it doesn't work anymore.
So basically my question is, why is there a maximum number of characters in my output loop and how can I bypass it ? Thanks, I am very confused.
I am trying to extract major keywords from a text or sentence using python. I am using python's RAKE module. The following python code works well in the console. But, when I am trying to call the python script from PHP, the script does not parse any new text or sentence which I stored in a php variable, and instead outputs the old text/sentence even though I commented out it within the python script and replaces it with sys.argv[1] argument. In various ways, within PHP I tried to solve this problem using PHP's exec and passthru commands without any luck and so I finally decided to post my problem here.
PHP script
$var1 = 'The extra sleep will help your body wash out stress hormones.';
Technique(1)
$output = exec("python rake_tutorial.py .$var1");
Technique(2)
$output = exec('python rake_tutorial.py ' .$var1, $result);
Technique(3)
$command = 'python rake_tutorial.py ' . $var1;
$output = passthru($command);
Technique(4)
$output = exec("python rake_tutorial.py $var1", $result);
echo '<pre>' . print_r($result, true);
Here is my Python code
__author__ = 'a_medelyan'
import rake
import operator
import sys
# EXAMPLE ONE - SIMPLE
stoppath = "SmartStoplist.txt"
# EXAMPLE TWO - BEHIND THE SCENES (from https://github.com/aneesha/RAKE/rake.py)
# 1. initialize RAKE by providing a path to a stopwords file
rake_object = rake.Rake(stoppath)
# text = "What you use depends on your baby's age and physical development."
# 1. Split text into sentences
sentenceList = rake.split_sentences(text)
# generate candidate keywords
stopwordpattern = rake.build_stop_word_regex(stoppath)
phraseList = rake.generate_candidate_keywords(sentenceList, stopwordpattern)
print "Phrases:", phraseList
# calculate individual word scores
wordscores = rake.calculate_word_scores(phraseList)
# generate candidate keyword scores
keywordcandidates = rake.generate_candidate_keyword_scores(phraseList, wordscores)
for candidate in keywordcandidates.keys():
print "Candidate: ", candidate, ", score: ", keywordcandidates.get(candidate)
# sort candidates by score to determine top-scoring keywords
sortedKeywords = sorted(keywordcandidates.iteritems(), key=operator.itemgetter(1), reverse=True)
totalKeywords = len(sortedKeywords)
# for example, you could just take the top third as the final keywords
for keyword in sortedKeywords[0:(totalKeywords / 3)]:
print "Keyword: ", keyword[0], ", score: ", keyword[1]
print rake_object.run(sys.argv[1])
sys.stdout.flush()
# print rake_object.run(text)
Looks like your exec command is going wrong.Try the following command:
$var1 = 'The extra sleep will help your body wash out stress hormones.';
$output = exec("python rake.py '".$var1."'");
Hope this helps!
Just thought I'd mention that there is a RAKE implementation in php https://github.com/artofzen/RAKE-PHP
Is it possible to pass BASH associative arrays as argv to PHP scripts?
I have a bash script, that collects some variables to a bash associative array like this. After that, I need to send it to PHP script:
typeset -A DATA
DATA[foo]=$(some_bash_function "param1" "param2")
DATA[bar]=$(some_other_bash_function)
php script.php --data ${DATA[#]}
From PHP script, i need to access the array in following manner:
<?php
$vars = getopt("",array(
"data:"
));
$data = $vars['data'];
foreach ($data as $k=>$v) {
echo "$k is $v";
}
?>
What I've tried
Weird syntax around the --data parameter follows advice from a great post about bash arrays from Norbert Kéri how to force passed parameter as an array:
You have no way of signaling to the function that you are passing an array. You get N positional parameters, with no information about the datatypes of each.
However this sollution still does not work for associative arrays - only values are passed to the function. Norbert Kéri made a follow up article about that, however its eval based solution does not work for me, as I need to pass the actual array as a parameter.
Is the thing I'm trying to achieve impossible or is there some way? Thank you!
Update: What I am trying to accomplish
I have a few PHP configuration files of following structure:
<?php
return array(
'option1' => 'foo',
'option2' => 'bar'
)
My bash script collects data from user input (through bash read function) and stores them into bash associative array. This array should be later passed as an argument to PHP script.
php script.php --file "config/config.php" --data $BASH_ASSOC_ARRAY
So instead of complicated seds functions etc. I can do simple:
<?php
$bash_input = getopt('',array('file:,data:'));
$data = $bash_input['data'];
$config = require($config_file);
$config['option1'] = $data['option1'];
$config['option2'] = $data['option2'];
// or
foreach ($data as $k=>$v) {
$config[$k] = $v;
}
// print to config file
file_put_contents($file, "<?php \n \n return ".var_export($config,true).";");
?>
This is used for configuring Laravel config files
Different Approach to #will's
Your bash script:
typeset -A DATA
foo=$(some_bash_function "param1" "param2")
bar=$(some_other_bash_function)
php script.php "{'data': '$foo', 'data2': '$bar'}"
PHP Script
<?php
$vars = json_decode($argv[1]);
$data = $vars['data'];
foreach ($data as $k=>$v) {
echo "$k is $v";
}
?>
EDIT (better approach) Credit to #will
typeset -A DATA
DATA[foo]=$(some_bash_function "param1" "param2")
DATA[bar]=$(some_other_bash_function)
php script.php echo -n "{"; for key in ${!DATA[#]}; do echo - "'$key'":"'${DATA[$key]}'", | sed 's/ /,/g' ; done; echo -n "}"
this does what you want (i think) all in one bash script. You can obviously move the php file out though.
declare -A assoc_array=([key1]=value1 [key2]=value2 [key3]=value3 [key4]=value4)
#These don't come out necesarily ordered
echo ${assoc_array[#]} #echos values
echo ${!assoc_array[#]} #echos keys
echo "" > tmp
for key in ${!assoc_array[#]}
do
echo $key:${assoc_array[$key]} >> tmp # Use some delimeter here to split the keys from the values
done
cat > file.php << EOF
<?php
\$fileArray = explode("\n", file_get_contents("tmp"));
\$data = array();
foreach(\$fileArray as \$line){
\$entry = explode(":", \$line);
\$data[\$entry[0]] = \$entry[1];
}
var_dump(\$data);
?>
EOF
php file.php
the escaping is necessary in the cat block annoyingly.
I've created two programs in C. The first gets a number and prints the double value of it and the second prints the quadruple. I want to execute them
through PHP. I've done it using proc_open and it works fine if I execute only one of the programs each time. I have to give a number to the
first program and pass its output as input to the second program. When though I use two proc_open to create the two processes,the whole thing doesn't work.
What I want to do is something like this:
$process1 = proc_open($command_exe1, $descriptorspec1, $pipes1, $cwd);
$process2 = proc_open($command_exe2, $descriptorspec2, $pipes2, $cwd);
fwrite($pipes1[0], $posted);
fwrite($pipes2[0], $pipes1[1]);
fclose($pipes1[0]);
fclose($pipes2[0]);
while(!feof($pipes1[1])) {
$StdOut1 = stream_get_contents($pipes1[1]);
}
echo $StdOut1;
while(!feof($pipes2[1])) {
$StdOut2 = stream_get_contents($pipes2[1]);
}
echo $StdOut2;
fclose($pipes1[1]);
fclose($pipes2[1]);
proc_close($process1);
proc_close($process2);
I know that it's a wrong way of doing it but I can't think of anything else so...any help would be welcome.
Note: I'm working on Windows.
If process can run separately one after another
You can try put "in-steps",
/** step 1*/
$process1 = proc_open($command_exe1, $descriptorspec1, $pipes1, $cwd)
...
while(!feof($pipes1[1])) {
$StdOut1 = stream_get_contents($pipes1[1]);
}
echo $StdOut1;
/** step 2*/
$process2 = proc_open($command_exe2 $descriptorspec2, $pipes2, $cwd)
while(!feof($pipes2[1])) {
...