Search code examples
phpexecraspbian

PHP exec() works in command line but not in web


I'm trying to use jarun's "googler" in a PHP script in order to search YouTube and find the URL of the first result. The command I'm executing is googler --np --json -C -n 1 -w youtube.com -x <name of youtube video>, and it works perfectly on my local machine. Here is my code:

<?php
exec("googler --np --json -C -n 1 -w youtube.com -x thomas the dank engine", $results);
var_dump($results);
?>

When I execute this in the command line, it works perfectly as it should, but when I do it via a web browser or a GET request, it does not work. I am aware that it is being executed as another user. In my case, it's the user www-data, so I gave that user full sudo permissions without a password, and did the following commands:

sudo -u pi googler --np --json -C -n 1 -w youtube.com -x thomas the dank engine

as well as

su - pi -c 'googler --np --json -C -n 1 -w youtube.com -x thomas the dank engine'

neither of these worked. Does it have to do with googler? What am I doing wrong?

When adding 2>&1 to the command, I get the following error message:

stdout encoding 'ascii' detected. googler requires utf-8 to work properly. The wrong encoding may be due to a non-UTF-8 locale or an improper PYTHONIOENCODING. (For the record, your locale language is and locale encoding is ; your PYTHONIOENCODING is not set.) Please set a UTF-8 locale (e.g., en_US.UTF-8) or set PYTHONIOENCODING to utf-8.


Solution

  • Try putting:

    putenv("PYTHONIOENCODING=utf-8");
    

    in the script before calling exec(). googler apparently requires the locale or this environment variable to be set.