Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Created September 8, 2023 03:18
Show Gist options
  • Select an option

  • Save code-boxx/6a197bb6aac28710e13476978bd8dfd0 to your computer and use it in GitHub Desktop.

Select an option

Save code-boxx/6a197bb6aac28710e13476978bd8dfd0 to your computer and use it in GitHub Desktop.
PHP Call Python Script

WAYS TO CALL PYTHON FROM PHP

https://code-boxx.com/call-python-scripts-from-php/

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

print("Hello from Python CLI.")
<?php
$script = __DIR__ . DIRECTORY_SEPARATOR . "1a-cli.py";
$result = shell_exec("python $script");
echo "PHP got the result - $result";
# pip install Flask
# (A) LOAD FLASK
from flask import Flask
app = Flask(__name__)
# (B) DUMMY ENDPOINT
@app.route("/")
def hello():
return "Hello from Python CURL."
# (C) GO!
if __name__ == "__main__":
app.run(host = "localhost", port = "8008")
<?php
$c = curl_init();
curl_setopt($c, CURLOPT_URL, "http://localhost:8008/");
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($c);
echo "PHP got the result - $result";
<!DOCTYPE html>
<html>
<head>
<title>DUO SCRIPTO</title>
<meta charset="utf-8">
</head>
<body>
<script>
// (A) CALL PYTHON SCRIPT
function callPY () {
fetch("http://localhost:8008", {
method : "POST",
mode : "cors"
})
.then(res => res.text())
.then(res => callPHP(res))
.catch(err => console.error(err));
}
// (B) CALL PHP SCRIPT
function callPHP (res) {
// (B1) DATA FROM PYTHON
let data = new FormData();
data.append("data", res);
// (B2) FETCH PHP
fetch("http://localhost/3c-fetch.php", {
method : "POST",
body : data
})
.then(res => res.text())
.then(res => console.log(res))
.catch(err => console.error(err));
}
// (C) GO!
callPY();
</script>
</body>
</html>
# pip install Flask
# (A) LOAD FLASK
from flask import Flask, Response, request
app = Flask(__name__)
# (B) ALLOWED ORIGINS
allowed = ["http://localhost", "https://localhost"]
# (C) DUMMY ENDPOINT
@app.route("/", methods=["POST"])
def hello():
print(request.environ["HTTP_ORIGIN"])
if "HTTP_ORIGIN" in request.environ and request.environ["HTTP_ORIGIN"] in allowed:
response = Response("Hello from Python FETCH.", status=200)
response.headers.add("Access-Control-Allow-Origin", request.environ["HTTP_ORIGIN"] )
response.headers.add("Access-Control-Allow-Credentials", "true")
return response
else:
return Response("Not Allowed", status=405)
# (D) GO!
if __name__ == "__main__":
app.run(host = "localhost", port = "8008")
<?php
echo "PHP received - " . $_POST["data"];
# (A) LOAD SOCKET MODULE
import socket
# (B) CREATE SOCKET SERVER
s = socket.socket()
s.bind(("127.0.0.1", 8008)) # bind to 127.0.0.1:8008
s.listen(1) # allow only 1 client
print("Ready")
# (C) ACCEPT CONNECTION
conn, addr = s.accept()
print("Connection from: " + str(addr))
while True:
data = conn.recv(1024).decode()
if data:
print("Received: " + str(data))
break
conn.close()
<?php
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, "127.0.0.1", "8008");
socket_write($socket, "Hello from PHP!");
socket_close($socket);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment