Reputation: 1
I have a python face recognition script that uses opencv and face_recognition module to detect and match faces. I want to implement this via a php file. So that whenever the php file is opened the face recognition script starts and opens the open-cv window. However all i am getting is a blank page. The script runs if it has only print("hello world") written in it. But the real script wont start using the same method. I have both the php and python files in the same directory.
The php codes i have tried are :
<?php
$command_exec = escapeshellcmd('python test.py');
$str_output = shell_exec($command_exec);
echo $str_output;
?>
This one just prints the first print line of the program which says "now opening face recognition window"
<?php
$command_exec = escapeshellcmd('python test.py');
shell_exec($command_exec);
?>
This one just gives a blank page
I was expecting the face recognition window to open as it would if i ran the python script directly
Now the thing is I am not supposed to use opencv-php. Neither can i implement the face recognition directly on the webpage. For my purposes i need to run the python script from the php file and then run the face recognition.
Upvotes: 0
Views: 365
Reputation: 1705
Modify your PHP code:
<?php
exec("python3 /path/to/test.py > /dev/null 2>&1 &");
echo "Python script started!";
?>
This command runs the script in the background. However, the OpenCV window might still not open if the web server user lacks GUI access.
Step 1: Create a Python server (e.g., Flask) that runs the face recognition script when triggered:
Python:
from flask import Flask
import subprocess
app = Flask(__name__)
@app.route('/run-face-recognition', methods=['GET'])
def run_face_recognition():
subprocess.Popen(["python3", "test.py"])
return "Face recognition script started!"
if __name__ == "__main__":
app.run(port=5000)
Step 2: Start the Flask server:
Bash
python3 flask_server.py
Step 3: Trigger the script from PHP:
PHP
<?php
$url = 'http://localhost:5000/run-face-recognition';
file_get_contents($url);
echo "Face recognition script triggered!";
?>
This approach decouples the web server (PHP) from the GUI constraints and ensures smoother execution.
3. Use a Desktop Environment Ensure the Python script runs under a user with GUI access. Modify the PHP script to switch the user to the one logged into the desktop session.
Modify test.py:
**Python**
import os
import cv2
os.environ["DISPLAY"] = ":0" # Set the display variable for GUI access
# Your OpenCV code here
Ensure the web server has permissions to access the GUI session:
Bash
sudo xhost +SI:localuser:www-data
Modify PHP to execute the script:
PHP
<?php
exec("python3 /path/to/test.py");
echo "Face recognition started!";
?>
4. Debugging Tips Test if the Python script runs correctly outside the PHP context:
Bash
python3 /path/to/test.py
Log errors to understand what’s failing:
PHP
<?php
$output = shell_exec('python3 /path/to/test.py 2>&1');
echo "<pre>$output</pre>";
?>
Upvotes: 1