I have a python flask application, but I have some old php scripts that I would want to reuse.
I am trying to parse some data from my flask application. When accessing it, company login password is needed, so "curl" in php wouldn't really work. So I am thinking of parsing the data to the php scripts through render_template.
Is it possible to do something like this :
data= <some data>
#app.route('/test')
def test():
return render_template('my_php_scripts.php',input_data=data)
While in my php script, I do:
<?php
$DataString=**{{input_data}}**
?>
If not, what would be a good way to do it?
So if you want process the php in python, you'll need to do something like
data = "Charles"
from subprocess import call
call(["php", "my_php_scripts.php", data])
where your php script looks something like
<?php
$DataString = $argv[1];
echo "Eat nachoes, $DataString!\r\n";
presuming the data is something fairly simple, or maybe you can convert it into a JSON if it's a more complex object and transfer it in that way.
Related
I want to send data from php to python and make some computations. After that I want to send result of that. The problem is I cannot send data from php to python.
python.php
username is working but shell_exec or python have problem
<?php
if(isset($_POST["username"])){
$nick = $_POST["username"];
echo shell_exec("python new.py '$nick'");
$jsonData = $_POST["prediction" ];
echo $jsonData;
}
?>
new.py
When I run python it prints C:\wamp\www\MLWebsite\website\new.py but it should be parameter
import pymysql.cursors
import sys
import urllib2, urllib
import requests
x=sys.argv[0]
print x
I want to get some idea about sending result because end of new.py
mydata=[('prediction','BIO')]
mydata=urllib.urlencode(mydata)
path='http://localhost/MLWebsite/website/python.php' #the url you want to POST to
req=urllib2.Request(path, mydata)
req.add_header("Content-type", "application/x-www-form-urlencoded")
page=urllib2.urlopen(req).read()
print page
I use Firebug plugin in Firefox and this error is also shown in webpage.
( ! ) Notice: Undefined
index: prediction in C:\wamp\www\MLWebsite\website\python.php on line
6 Call Stack #TimeMemoryFunctionLocation 10.0006245144{main}( )..\python.php:0
I assume the reason that you want to do it this way (i.e., using PhP to interact with user but having Python actually do the processing) is that you want to take advantage of python language for some tasks, but avoid having to use a separate webframework just for those tasks.
One way to accomplish it (albeit perhaps not the way you want to solve it) is to have PhP write the data to a text file with delimiters separating different chunks of data. Then have PhP call the Python file, which knows to read the text file.
In my example below Python writes to a file and PhP can open it if it wants, but you can go the other way as well. PhP could write to a .txt file, Python can read and manipulate, and then save to the same or different .txt file, and PhP can open and render the results.
Basically, you are using a .txt file as 'memory'.
This is an example:
<?php
echo "<h1>This is PhP!</h1>";
$returnedValue = shell_exec('/home/sitename/public_html/pythonFile.py');
echo $returnedValue; //This line may not be needed if there is nothing to return.
echo "<h2> Completed </h2>";
//Once the 'Complete' Above Renders in the Browser You Know that Python Did Whatever it Was Going to Do to the .txt File
//Now, if you want to have PhP Open the .txt File and Display it You Can
?>
#THIS IS PYTHON
#!/usr/bin/env python
file_object = open("NameOfTextFile.txt", "w+")
file_object.write("Hello World!")
file_object.close()
I realize this question is old, but I recently had the same issue and this is how I tried to resolve it. Hopefully it helps someone.
I think your question needs refinement.
From what I can tell, your python program is doing what one would expect.
$ cat 0.py
#!/usr/bin/python
import sys
print sys.argv[0]
print sys.argv[1]
$ chmod 755 0.py
$ python 0.py foo
0.py
foo
$ ./0.py foo bar
./0.py
foo
So, if your python program is prining 'new.py' as you wrote the question, I think that's expected behavior. Why you're passing unsanitized user input to a system call is another question. Why you're using a system call at all (why not set up a webservice with your python program?) is yet a further question.
I hope this helps.
I have a PHP app that I want to convert to django. But I want to do it stages. All the heavy lifting is in the PHP code, so first, I want to just use templates and views to generate the HTML, but still call the PHP code. Then later convert the PHP to python. My issue is that the PHP code expects to get all it's input from the REQUEST object and I've consumed that in the view. Is there any way I can somehow supply that to the PHP code?
Is there some way python can communicate like curl ... it needs to send the request string in the body of a POST request to the URL that will route to the PHP script and get the output back.
You can simply read the output with urllib2 (or one of the many other libraries) and return the response.
import urllib2
from django import http
def some_django_view(request):
fh = urllib2.urlopen('http://your_php_page/?' + request.GET.urlencode())
return http.HttpResponse(fh.read())
i'm searching the inet for around 3 days now and i'm stuck at this.
I got a MySQL Database and a php Script, as well as a Game made in UE4.
UE4 uses c++.
So now i want to send requests from the c++ game to the php script and that shall interact with the database.
For example create an account or login. I also want to pass the mysql query result of the php script to my c++ class.
I tried using HttpRequest, but i can't get data from php to c++ with that.
Maybe you can, but i don't understand it at all.
What i accomplished by now is that you can send a POST request from the game to the php script and pass variables so that the script uses them to perform the mysql query.
But how can i pass data from the php file to c++ now? The response i get is always the whole site (head and body) and i don't know where i could save the query result to pass it to the c++ code.
I'm a full beginner here, so go easy on me. I read so many different posts and blogs that my brain hurts like hell ): I hope someone can tell me how to do this easily or at least give me a hint on what i have to google and what i could use. I don't need a full tutorial, just a name of a library better than the Http.h (if simple HttpRequest cant manage this) would be enough. ): I'm really frustrated...
eXi
The PHP script should retun a HTTP response reduced to a bare minimum. It doesn't even need to be a HTML document:
<?php
// file: api.php
$param = $_POST['myparam'];
$foo = bar($param); // $foo contains e.g. "1,ab,C"
echo $foo; // if you opened http://myhost.com/api.php in a browser
// all you would see is "1,ab,C"
// (which is not a valid HTML document, but who cares)
?>
Then parse this HTTP response (a plain string, that is) from your game. You can use your own data format, or use a well-known format of your choice (XML or JSON are good candidates).
The json object in unreal is pretty good, so I would recommend outputting json from your php script. Json in php is a pretty natural workflow.
<?php
$obj['userid'] = 5476;
$obj['foo'] = 'bar';
echo json_encode($obj);
php?>
That will echo out
{"userid":5476,"foo":"bar"}
If that's all you output in your script then it's pretty straightforward to treat that as a string and populate an unreal json object with it.
FString TheStuffIGotFromTheServer;
TSharedPtr<FJsonObject> ParsedJson;
TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(TheStuffIGotFromTheServer);
if (FJsonSerializer::Deserialize(JsonReader, ParsedJson))
{
FString foo = ParsedJson.GetStringField("foo");
double UserId = ParsedJson.GetNumberField("userid");
}
Check out the unreal json docs to get a feel for what you can do with it.
I created a web based application using PHP and MySQl. It has a login page Login.php, which is the starting page. I want to integrate my php code in ruby code. I want to include this Login.php page in the ruby application so that it can display the page. Is there any possible solution?
Hm, your "exec("php Login.php")" idea is interesting. But you should redirect the output then. You can get the output like this:
$output = array();
$returnStatus = null;
$command = 'php Login.php';
exec($command, $output, $returnStatus);
// Your output is now in the $output array.
See http://de2.php.net/manual/de/function.exec.php for further documentation. Also keep in mind that the user which is used for your anonymous calls should have the permission to execute php from cli and has access to the file you need. Things can get even more "funny" if you use IIS.
But since you are using ruby try this first:
require 'net/http'
source = Net::HTTP.get('stackoverflow.com', '/index.html')
I got it from the following wuestion of another user: How to get the HTML source of a webpage in Ruby.
Your code would look like this:
require 'net/http'
source = Net::HTTP.get('your-wesome-domain-or-maybe-localhost.com', '/Login.php')
Also alter the path of the second parameter if needed.
With this you should also be able to execute the script and get your HTML output by simply triggering it with ruby.
I have a PHP script (news-generator.php) which, when I include it, grabs a bunch of news items and prints them. Right now, I'm using Python for my website (CGI). When I was using PHP, I used something like this on the "News" page:
<?php
print("<h1>News and Updates</h1>");
include("news-generator.php");
print("</body>");
?>
(I cut down the example for simplicity.)
Is there a way I could make Python execute the script (news-generator.php) and return the output which would work cross-platform? That way, I could do this:
page_html = "<h1>News and Updates</h1>"
news_script_output = php("news-generator.php") //should return a string
print page_html + news_script_output
import subprocess
def php(script_path):
p = subprocess.Popen(['php', script_path], stdout=subprocess.PIPE)
result = p.communicate()[0]
return result
# YOUR CODE BELOW:
page_html = "<h1>News and Updates</h1>"
news_script_output = php("news-generator.php")
print page_html + news_script_output
PHP is a program. You can run any program with subprocess.
The hard part is simulating the whole CGI environment that PHP expects.
maybe off topic, but if you want to do this in a way where you can access the vars and such created by the php script (eg. array of news items), your best best will be to do the exec of the php script, but return a json encoded array of items from php as a string, then json decode them on the python side, and do your html generation and iteration there.
I think the best answer would be to have apache render both pages separately and then use javascript to load that page into a div. You have the slight slowdown of the ajax load but then you dont have to worry about it.
There is an open-source widget thing that will run multiple languages in 1 page but I cant remember what its called.
You could use urllib to get the page from the server (localhost) and execute it in the right environment for php. Not pretty, but it'll work. It may cause performance problems if you do it a lot.