Execute Python script from Php

Try this out, it should be working:

<?php 
system("cd /usr/lib/cgi-bin");
system("sudo python script.py");
?>

Or even this:

<?php 
system("cd /usr/lib/cgi-bin && sudo python script.py");
?>

On an older Raspbian distribution you need to place your file in /var/www/file.py. So in your file.php you add:

{
    exec("sudo python /var/www/file.py");
}

On a newer Raspbian Jessie you need to place your file in /var/www/html/file.py, so in your file.php you need to add:

{
    exec("sudo python /var/www/html/file.py");
}

Or just any file.py

<?php
{
  exec("sudo python test.py");
}

?>

Note: For this to work you need to edit a file first to add these lines to allow passwordless sudo

sudo nano /etc/sudoers

then go to the bottom and add this

pi ALL=(ALL) NOPASSWD: ALL<br>
www-data ALL=(ALL) NOPASSWD: ALL

You can't use sudo from a PHP script. Apache is running from an user (www-data generaly), so edit this file : /etc/sudoers

Then add this line :

www-data ALL=(ALL) NOPASSWD:ALL

Care ! this will authorize all functions to be called by a PHP script, you can adapt changing "ALL" by your script or Python command.

Then precise your user in your exec command :

<?php
exec('sudo -u www-data python /usr/lib/cgi-bin/script.py')