Victor Meunier
Victor Meunier

Reputation: 37

Executing bash script from PHP on raspbian

I have a script that calls fswebcam to capture a jpg with my USB camera. I've made it executable with "chmod +x webcam.sh" :

File : /var/www/html/webcam.sh

#!/bin/bash
DATE=$(date + "%Y-%m-%d_%H%M")
fswebcam -r 640x480 /home/pi/webcam/$DATE.jpg

This is working fine in command line without sudo, so I've made a small PHP page :

File : /var/www/html/index.php

<?php
 $output = shell_exec('sh /var/www/html/webcam.sh');
 echo "<pre>$output</pre>";
?>

When I go to the webpage, I just get a blank page and no jpg is created in my webcam folder.

I got the following error : Apache2 error log

So I've tried modifying my call in PHP, to :

<?php
$output = shell_exec('/usr/bin/sudo /bin/bash /var/www/html/webcam.sh');
echo "<pre>$output</pre>";
?>

I've also add the following to sudoers file

www-data ALL=NOPASSWD: /path/to/script

But I still get the error : apache2 log error

I've tried everything from this thread : How to run .sh script with php?

Do you have any idea ?

Thanks in advance,

Victor

Upvotes: 0

Views: 620

Answers (1)

Marco
Marco

Reputation: 7287

First off:

  • Don't use sudo if you don't have a very good reason for it.
  • sh does not necessarily invoke bash.
  • sudo expects a password, but you didn't provide any hence the error.

I suggest trying with exec instead of shell_exec (there is a difference between the two):

<?php
    exec('/var/www/html/webcam.sh', $output, $exitCode);

    echo 'Exit code: '.$exitCode.' <hr />';
    echo implode('<br />', $output);

Another source of your problem could be permission related:

The webserver usually runs as a different user.

Make sure the webserver can actually write to the output directory.

Upvotes: 1

Related Questions