php exec function not running correctly - php

I compile my c++ file by this command:-
g++ main.cpp -o main pkg-config --cflags --libs opencv
This runs fine. Now when i run main file by command line using this command './main', it's runs fine, and stared my webcam.
But when i write code in php to execute this file by php code, It's also runs but my webcam does not found, And gives me an error.
starting cam No webcam where found
I don't know what's the reason behind this.
I am putting some piece of code of my files.
main.cpp
CvMemStorage *storage = cvCreateMemStorage(0);
CvHaarClassifierCascade *cascade = (CvHaarClassifierCascade*)cvLoad("data/haarcascade_frontalface_default.xml");
printf("starting cam\n");
CvCapture* capture = cvCaptureFromCAM(CV_CAP_ANY);
if(capture == 0)
{
printf("No webcam where found");
return 1;
}
CvScalar red = CV_RGB(250,0,0);
// counters used for frame capture
int happy_count = 0;
int sad_count = 0;
printf("starting recognition\n");
output.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
echo shell_exec('./main');
Error on run php:- starting cam No webcam where found.
Note:-Works fine on terminal

That's my suggestion only, but could you check which user is executing programs while using PHP exec? Probably apache (are you using that?) has own user, which has no access to webcam. I suggest to try running apache as regular user to check if that helps, or give access to webcam for your apache user.
Here you have some help in that matter.
https://serverfault.com/questions/125865/finding-out-what-user-apache-is-running-as

Seems like permissions issue to me. When you execute the program through php script, it is executed by the user that runs the server process. I am guessing you are using apache2 webs server to serve php content, which runs as user www-data in Ubuntu. If this is true, you just add the user www-data to the group video.
sudo usermod -a -G video www-data
If you are using another web server or a different linux distribution, or your web server runs with a different user, you need to modify the command accordingly.

Related

PHP/Ubuntu - QxcbConnection: Could not connect to display aborted

I am using a php script on my apache/ubuntu server to call a bash script that triggers an application taking a python script as an argument (IDAPro).
PHP Code
chdir('/var/www/dashboard/team/static/sql');
$output = exec('sudo -u rohan ./start.sh');
Now, the above code works fine if I run the PHP file from the terminal - but only if I run it as the root user. Needless to say, if I execute the bash file directly it runs too.
But when I run the PHP file on the browser, it doesn't work and I get the following error in the apache error log:
QXcbConnection: Could not connect to display
Aborted
I understand that Apache/php runs as 'www-data' user (used the 'whoami' to verify), and that is why I have the sudo in my exec. I have tweaked and tinkered the permissions for both users to no avail. When I run the php file from the terminal as the 'www-data' user, it throws no error but does not do anything except display the random echo tags I at the start and end of the script to debug it.
I am a linux novice, so any help is greatly appreciated.
Okay, I finally managed to solve it.
The issue is not with the permissions, but it is with the environment variables.
I had to include the following line in my bash script
export DISPLAY=':0.0'
Note that setting the variable in the terminal and running the script does not work. The line needs to be inside the script.
I assume this is because the DISPLAY variable is not set if you run the script as any user other than root, which is what happens in case of Apache/PHP where the script is executed as the 'www-data' user.
perhaps you could use something like the following at the top of your script:
if [ "$(id -un)" != "rohan" ]; then
exec sudo -u rohan $0 "$#"
fi
export XAUTHORITY=/home/rohan/.Xauthority
export DISPLAY=:0

No output on web page PHP while executing shell command

I am trying to execute Linux shell command from php but there is no output on web page. If I am trying to execute the php page from linux cosole its working fine.
PHP Code:
<?php
$result = shell_exec('asterisk -rx "core show channels concise"');
$ccount =shell_exec('asterisk -rx "core show channels count"');
echo $result;
echo $ccount;
?>
Above code is not giving any output on web page. But on linux console its woking. e.g.
[abc#host sysadminman]# php myfile.php
Asterisk control socket permissions can also be changed easily in /etc/asterisk.conf:
[files]
astctlpermissions = 0660
astctlowner = root
astctlgroup = apache
astctl = asterisk.ctl
First of all your question is incomplete as you not showing what is expected output. But aside from this you are doing a few common mistakes there.
First you are testing your script as root (# php ...) but your httpd is NOT serving your scripts as root. So your tests are useless. You should switch to right user (most likely www-data and then check to run your script from shell. Most likely it will fail for one of two common reasons - insufficient permissions to run asterisk program or incomplete $PATH not pointing to the place where asterisk is.
I agree to Marcin.
I would suggest you write script to execute those commands and put result to some storage (such as text or database). Use cron to run it in root. Then you read the data from storage on web page.
If you want real time response, you have to run cron all the time though it consume server resource. That is trade-off you have to consider. Its depends on what you wanna achieve from the web site.
Use sudo to run thoes commands as root or Asterisk user. You can configure sudo to allow execution without password to only specific commands.
check disable_functions in php.ini. Mb shell_exec just off for web server

Running imagesnap in PHP with Mac Server

I am trying to develop a small site to take snapshots of my house using a webcam connected to to my mac mini at home. The mac mini is running OS X Server. The Webcam is a Logitech HD Pro Webcam C920 (USB connected). It is based on PHP and HTML5 (no other code besides CSS).
My development machine is a MacBook Pro using the internal iSight camera. It is not running OS X server; I manually enabled apache and PHP. While developing the site on my laptop, everything worked flawlessly. When I installed it on my mac mini the imagesnap program turns on the camera but never finishes; I have to manually kill the process, and the snapshot is never created.
The following error is logged:
imagesnap[2363]: *** QTCaptureSession warning: Session received the following error while decompressing video: Error Domain=NSOSStatusErrorDomain Code=-12903 "The operation couldn’t be completed. (OSStatus error -12903.)". Make sure that the formats of all video outputs are properly configured.
This is only when running it from the site directly. If I run the same program from the command-line, it works just fine... even running it as the _www user!
sudo -u _www bin/imagesnap images/snapshot_$DATE.jpg
This is the code that does the call in PHP:
<?php
if(isset($_POST['submit'])) {
system('bin/run_imagesnap.sh', $return_value);
if ($return_value) {
echo "The command failed.";
}
}
?>
I was unable to figure out how to write the date to the output filename (I'm a noob with PHP), so I used a bash script to do it for me (I'm better with BASH):
#!/bin/bash
DATE=`date +"%m-%d-%y_%T"`
bin/imagesnap -q -w 3 images/snapshot_$DATE.jpg
I've also tried exec(), passthru(), and shell_exec() all with the same results.
Finally, I've also tried the following: Create test.php, put code:
<?php
system('bin/run_imagesnap.sh', $return_value);
if ($return_value) {
echo "The command failed.";
}
?>
and ran it on the command-line as the _www user using the php-cli:
sudo -u _www php test.php
and it also worked just fine (created the snapshot file and did not give error).
I'm thinking maybe it has something to do with the OS X server app, but google searches return nothing.
I'm stumped. Why does it break when I run the same exact code on the browser but works fine on the command-line using the same exact tools and user?
Unknown if this is the correct way, but I ended up using sudo to run the script.
visudo
and then give the _www user passwordless root access to the script:
_www ALL=NOPASSWD: /path/to/script
and now it works. There's always more than one way to skin a cat..

Why cannot PHP execute a command from web browser?

This is really simple but I cannot get it to work at all. Spent many hours and I've always give up. I created php script called copy.php and it should call a python script called copy.py.
I want to execute a command line like this
<?php exec('/var/www/html/copy.py'); ?>
Really simple.
Why cannot I get the python script executed from php exec()? The function inside python script is to get a copy of error_log from a different directory (outside of Apache) into html directory.
If I run that from a terminal
> php copy.php
It did execute the function and made a copy. Why is that the web browser isn't doing it?
Let me simplify this:
why cannot exec("cp /var/log/httpd/error_log /var/www/html/path/to/php/script") work?
it works fine if I type it in terminal but not when run in a browser.
As others have alluded to, the difference is probably permissions. When you run a command from the command line, you're generally not the same users as your apache script is running as.
Put another way, if from the command line you type whoami, you'll probably get whatever name your user account is.
The echo exec('whoami'); from within php shows who the script is running as, which is Apache.
So, whatever command you're trying to run from your web server isn't available to run as the Apache user. You mentioned you've been able to have exec("python /usr/diskpurge/script.py") work, but not to have exec('/var/www/html/copy.py') doesn't. This is due to in one instance you're running python, in the other you're trying to execute your copy.py script. If copy.py doesn't have execute permissions for the Apache user, you're not going to be able to run it from the browser.
Perhaps different settings apply for the Apache environment versus the command line.
Use error_reporting(E_ALL); and ini_set('display_errors', true) to see what errosr may come up.
It is possible that the Apache environment is prohibited from using exec or the fact that Apache runs under a different user that does not have execute rights on the python script.
sounds like a permission error. Check if your server is running with sufficient rights.
echo exec('whoami');
Set your error reporting to report all:
ini_set('display_errors', true);
error_reporting(E_ALL);
and check for errors..
If your whoami returns a user which is not a member of the SU family (linux) or administration (windows) then resite your permissions..
Linux:
Assign the user returned by whoami correct permissions to run python scripts.. Do not allow the resulted username to run as root with total administration powers.. This is a big no no
The only reason its not working is because you didn't set the write permissions!
Do:
sudo nano /etc/sudoers
And then put the following:
www-data ALL=(root) NOPASSWD:ALL

Executing a command line using php shell_exec() for initiating a camera on the server

I am using opencv for initiating the camera on my arch linux. Its getting initiated and works well when I actually do it from the command line on the server itself.
I want to initialize it using php. I tried doing it using shell_exec from PHP.
My PHP file looks like:
<?php
$output=shell_exec('LD_LIBRARY_PATH=usr/local/lib ./a.out 0 2>&1 1>/dev/null');
echo $output;
?>
It gives this output:
ERROR: capture is NULL
I am running this through my windows web browser as a client and the opencv and the related files are on the server that is my arch linux.
I want to start the camera and capture images when I run this php file from the windows web browser, but when executed it throws the error as mentioned.
While this may work when you are SSHed into your server. The webserver user is most likely different than the user you login as. Popular user ids/groups that webservers run as on Linux machines are http, www-data, nobody, and others.
From this point you have two options.
You can make sure the script you are trying to run from PHP (and all of it's children, if any) is able to be run by the webserver user.
You can modify your /etc/sudoers file which gives the webserver user access to elevate permissions for that script only. (NOTE: This potentially opens up security holes so be careful).
To find out what user your webserver runs as execute this: ps aux
Take a look at the output and the first column in the output lists the user that that process is running at. Here's an excerpt of my webserver (nginx) on one of my boxes:
www-data 26852 0.0 0.0 29768 3840 ? S Jun04 0:50 nginx: worker process
You can see that nginx runs with the user www-data here. You can also execute the command with grep to help you find the process quicker. Grep will only show you those lines which match what you send to it. Here's an example: ps aux | grep nginx
Ok now that you know what user the webserver is running as, let's try giving that user access to the script. Let's say your script is foo and is located in /usr/local/bin. You would do the following commands:
chown www-data /usr/local/bin/foo
After changing ownership on the file try to rerun your command again from your PHP page and see if it works.
For completeness I also said you could give your webserver user sudo privileges to that file. To do that you would need to append the following line to the bottom of your /etc/sudoers file:
www-data ALL= NOPASSWD: /usr/local/bin/foo
Then your shell_exec command could switch to this:
shell_exec('sudo /usr/local/bin/foo');
Please keep in mind that doing this would allow your webserver user to run the script as root which is incredibly dangerous in a variety of situations. However, the camera may require elevated permissions to work. I'm not sure what the permissions requirements are on the camera setup you are trying to invoke.
Good luck. Hope this helps!

Categories