Executing Python Script with PHP Variables - php

I am writing a simple application that uses information from a form, passes it through $_POST to a PHP script that executes a python script and outputs the results. The problem I am having is that my python script is not actually running with the arguments being passed in.
process3.php file:
<?php
$start_word = $_POST['start'];
$end_word = $_POST['end'];
echo "Start word: ". $start_word . "<br />";
echo "End word: ". $end_word . "<br />";
echo "Results from wordgame.py...";
echo "</br>";
$output = passthru('python wordgame2.py $start_word $end_word');
echo $output;
?>
Output:
Start word: dog
End word: cat
Results from wordgame.py...
Number of arguments: 1 arguments. Argument List: ['wordgame2.py']
At the top of my wordgame2.py, I have the following (for debugging purposes):
#!/usr/bin/env python
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
Why isn't the number of arguments being passed = 3?
(Yes, my form does send the data correctly.)
Any help is greatly appreciated!
Edit: I might add that it does run when I explicitly tell it the start and end word... something like this:
$output = passthru('python wordgame2.py cat dog');
echo $output

Update -
Now that I am aware of PHP, the mistake lies in using the single-quotes '. In PHP, single quoted strings are considered literals, PHP does not evaluate the content inside it. However, double quoted " strings are evaluated and would work as you are expecting them to. This is beautifully summarized in this SO answer. In our case,
$output = passthru("python wordgame2.py $start_word $end_word");
would work, but the following won't -
$output = passthru('python wordgame2.py $start_word $end_word');
Original answer -
I think the mistake lies in
$output = passthru("python wordgame2.py $start_word $end_word");
Try this
$output = passthru("python wordgame2.py ".$start_word." ".$end_word);

Thank you for your contributions. I have figured out my problem with this simple fix:
$command = 'python wordgame2.py ' . $start_word . ' ' . $end_word;
$output = passthru($command);
In order for passthru to properly handle the php variables, it needs to be concatenated into the string before executing.

well if I understood you want pass a big amount of text like content of something, so the right way is;
$output = passthru("python wordgame2.py ".json_encode($end_word)." ".json_encode($start_word));

Related

How to get a certain text from this function?

I'd like to know how to get the text Physical Address. . . . . . . . . : xx-xx-xx-xx-xx-xx from $cmd = system('ipconfig /all').
When I write $ cmd = system('ipconfig /all') there is atext displayed in my screen. Even without echoing the $cmd. How to remove the text but some portion of the text. I'd like to get 38 chars after the text Physical Address
note: more importantly to get a rid of the displayed text of system('ipconfig /all') but still contain it in a variable
You need to test a bit because i dont know exactly your IPCONFIG results (varies from OS to OS) but here is a very close to what you want:
<?php
$command = "ipconfig /all";
$output = shell_exec($command);
$output = explode(PHP_EOL, $output);
$output = $output[0];
$result = explode("Physical Address",$output);
echo substr($result[1],20,17);
?>
Keep in mind you may need to change echo substr($result[1],20,15); to fit your needs, as it varies depending how many network cards you have etc.
In addition to Mohammad's answer you could use output buffering.
something like:
ob_start();
system('ipconfig /all');
$output = ob_get_clean();
print_r( $output);
should capture everything coming back from the command. You can then manipulate it however you like as a string.
$val = shell_exec('ipconfig /all');
echo $val;
You can send second parameter to system function to get output of command:
system('ipconfig /all', $output); //$output is result of command
Also you can use shell_exec function to only return output and not echo by default as below:
$output = shell_exec('ipconfig /all');

Regex not interworking with mysqli

I have the following php code:
//Usual mysqli stuff before here --> works
while($post = $result->fetch_assoc()) {
$post_text = (string)$post['post_text'];
$regex = "/(" . (string)$some_var . " - )(.*?)( [A-Z]{4})/";
}
echo $post_text . "<br />";
echo $regex . "<br />";
preg_match($regex, $post_text, $matches);
echo count($matches);
Unfortunately I don't get any results back, even though my regex seems to work with this tool here: http://www.phpliveregex.com/
I also tried to put the result manually in a string like this:
$my_string = "blablablablabla - proper stuff where the regex will find smth"
Using this string, the code works, but just not with the string I get back from the db. What am I doing wrong here?
Thx in advance.
Made it work myself. Problem was that the string contained new lines so I am running now the following regex on the stuff received from the db:
preg_replace('/\s+/', ' ', $post_text)

How to escape backslashes in files

I am trying to work on a script but I am stuck in one place.
Eg. To get a php output I have used..
str_php = """
<?php
echo "Hello World!";
?>"""
php_file = open("index.php", "w")
php_file.write(str_php)
php_file.close()
Ok, so I get the output as it is....
<?php
echo "Hello World!";
?>
So my php code is running. all good till here. But, the problem starts from when I try using "\" and "\n" and "\r"
str_php = """
<?php
echo "Hello World!"; \n echo "How are you"; \n echo "God bless you";
?>"""
php_file = open("index.php", "w")
php_file.write(str_php)
php_file.close()
But here I dont get the output as it is.
<?php
echo "Hello World!";
echo "How are you";
echo "God bless you";
?>
And the "\" it just vanishes... at an output.
Eg. I want an output of a php hyperlink something like...
str_php = """<?php
print("$dirArray[$index]");
?>"""
php_file = open("index.php", "w")
php_file.write(str_php)
php_file.close()
and the output I get is...
<?php
print("$dirArray[$index]");
?>
The "\" is missing and the php does not run creating error.
print("$dirArray[$index]") - Original
print("$dirArray[$index]") - python output
Can any one help me out with "\", "\n", "\r" ??
Just use "\" to escape the "\" character.
Since it is common to want to have long strings containing several "\", Python also allows one
to prefix the string opening quotes if ar r (for "raw") - inside such
a string, no escaping of "\n" to chr(10) or "\t" to chr(9) happens:
>>> print (r"Hello \n world!")
Hello \n world!
You need to escape your "\" with another backslash writting it as "\\".
If you use "\n" it will be parsed and make a newline. Try to use '\n', strings enclosed in '\n' are not parsed and it should print out as you want it to.

escape character not working as expected

I am trying to create html content in PHP and for onclick event I have included a function named uchat for a div. The function takes a name parameter which is a string.
Like below:
$name = "Php string";
$echostr .= "<div onClick='uchat(\'$name\')'>
</div>";
But, passing a string value like this causes syntax error when div is clicked. Because, single quote is within a single quote. I have tried to escape it, but it still doesnt work.
The error is this:
SyntaxError: illegal character
uchat(\
I am not sure how to escape a string parameter and I have come across this problem so many times, Please help if you have a solution for this.
Thanks.
Escaped single quotes will conflict with outer ones:
$echostr .= "<div onClick=\"uchat('$name')\">
</div>";
Here are 2 clean and simple ways to do this:
1. Classic concat
$name = "Php string";
$str = "<div onClick=\"uchat('" . $name . "')\"></div>";
print $str;
2. Using sprintf (http://us3.php.net/manual/en/function.sprintf.php)
$name = "Php string2";
$str = sprintf("<div onClick=\"uchat('%s')\"></div>", $name);
print $str;
try like this
$echostr .= "<div onClick='uchat("$name")'></div>";
This works:
<?php
$name = "Php string";
$echostr .= <<< EOF
<div onClick="uchat('$name')"></div>
EOF;
echo $echostr;
?>
Output:
<div onClick="uchat('Php string')"></div>
In order to avoid escaping all double quotes and to make the html code more readable you can use EOF.
See it action : http://ideone.com/vRCCVH

PHP exec capture text

I am having a problem with capturing text when I make an exec call to a perl script that just prints a lot of text. What happens when I run the following code is I get a 1 word result: "Array". I need to be able to capture the results so that I can change them around just a little bit. Here is the code:
<?php
$lastline = exec("perl parseOutput.pl",$retVal);
echo $retVal;
?>
How do I work around this?
You have an array of the lines of text that was outputted.
Do something like this:
echo implode( "\n", $retVal);
Or
echo implode( "<br />\n", $retVal);
And you'll see all of the output generated by the perl script.
just use shell_exec()
$fullResult = shell_exec("perl parseOutput.pl");
echo $fullResult;

Categories