(Seemingly) no matter what command I try to run with PHP's system function, the command always does nothing and then fails with exit code 1. For example,
system("echo 'this should definitely work'", $retval);
sets $retval = 1. So does
system("dir", $retval);
as well as running an executable that I've written; when I run
vfmt -h cat.v
from cmd.exe the command works and returns with exit code 0, but running
system("vfmt -h cat.v", $retval);
again sets $retval = 1. This vfmt.exe file is in the same directory as the src.php script that is attempting these system calls.
I am nearly at my wit's end trying to figure out what's wrong. What could possibly be causing this issue?
You should check your php.ini for line like the next:
disable_functions =exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source
^^^^ ^^^^^^^^^^^^^^^^^^
and such.
Also check your "safe mode" status, (php ver. < 5.4) if you have enabled it you can only execute files within the safe_mode_exec_dir and so on...
More information in the doc and for the execution of commands here and especially for system here.
echo is invariably a shell internal command, not a separate executable. You need something more like
system('/bin/sh -c "echo \'foo\'"'); // unix-ish
system('cmd.exe /c echo foo'); // windoze
Most likely issue is that the "working directory" is not what you expect.
This is hidden as you're checking return value and not screen output; they are different.
Firstly, to monitor: try using exec http://au2.php.net/manual/en/function.exec.php as this will help you debug by giving both screen output and return value.
Secondly, to fix:
1 - Specify full paths to both the executable and included files. Assuming this is Windows (you refer to cmd.exe) then run
system("c:\PathToPhpFile\vfmt -h c:\PathToCatVFile\cat.v, $retval);
or
2 - Change the working directory before calling system() or exec() by using chdir() first.
(Or you can do the cd in a batch file (windows) or concatenate the commands in Linux; but this is less portable.)
You need to redirect the output of the command you're running with system() in order for it to run in the background. Otherwise, PHP will wait for program execution to end before continuing.
system('mycommand.exe > output.log', $retval);
system('mycommand.exe 2>&1', $retval);
Not sure how you're invoking your script, but perhaps you're running into a PHP max_execution_time (or related) limit. Something to investigate. Also, since you're running on windows, you may need to use absolute paths with your commands when executing system calls as the file you're invoking may not be in any defined PATH.
Related
I have a web server being hosted on a Raspberry Pi B+, running Raspbian. I always have a php "shell" that i can use, but it seems that mine might be messed up somehow. It is an html textarea, with the name="phptorun", and the action file just does eval($_POST['phptorun']);
Since I just have my RPi tucked under a table with no display, I use my phone alot to access the command line.
My question:
When i run something like system("ls"); i get output and the contents of the working directory is displayed. I am working on a C "compiler" (it just uses the command line gcc) but when i do system("gcc");
i get no output at all. i know that the command gcc does put out output, because i have done it before on a different computer.
So why is system("gcc"); not working?
And if gcc isnt installed, wouldnt i get output, just an error?
You need to get more information, it's possible that gcc outputs something to the STDERR for example, which you're missing when you use the system function.
Better try to use the exec function:
exec("gcc 2>&1", $output, $return_code);
Explanation:
gcc 2>&1 redirects STDERR output to the STDOUT
STDOUT is captured into the $output variable
command return code is in the variable $return_code
I have a script that uses passthru() to run a command. I need to set some shell environment variables before running this command, otherwise it will fail to find it's libraries.
I've tried the following:
putenv("LD_LIBRARY_PATH=/path/to/lib");
passthru($cmd);
Using putenv() doesn't appear to propagate to the command I'm running. It fails saying it can't find it libraries. When I run export LD_LIBRARY_PATH=/path/to/lib in bash, it works fine.
I also tried the following (in vain):
exec("export LD_LIBRARY_PATH=/path/to/lib");
passthru($cmd);
How can I set a shell variable from PHP, that propagates to child processes of my PHP script?
Am I limited to checking if a variable does not exist in the current environment and asking the user to manually set it?
I'm not 100% familiar with how PHP's exec works, but have you tried: exec("LD_LIBRARY_PATH=/path/to/lib $cmd")
I know that this works in most shells but I'm not sure how PHP doing things.
EDIT: Assuming this is working, to deal with multiple variables just separate them by a space:
exec("VAR1=val1 VAR2=val2 LD_LIBRARY_PATH=/path/to/lib $cmd")
You could just prepend your variable assignments to $cmd.
[ghoti#pc ~]$ cat doit.php
<?php
$cmd='echo "output=$FOO/$BAR"';
$cmd="FOO=bar;BAR=baz;" . $cmd;
print ">> $cmd\n";
passthru($cmd);
[ghoti#pc ~]$ php doit.php
>> FOO=bar;BAR=baz;echo "output=$FOO/$BAR"
output=bar/baz
[ghoti#pc ~]$
A couple things come to mind. One is for $cmd to be a script that includes the environment variable setup before running the actual program.
Another thought is this: I know you can define a variable and run a program on the same line, such as:
DISPLAY=host:0.0 xclock
but I don't know if that work in the context of passthru
https://help.ubuntu.com/community/EnvironmentVariables#Bash.27s_quick_assignment_and_inheritance_trick
I'm writing a class who let me access to recutils through PHP.
I have a 'database' file called books.rec in ../database/ and a script who runs my Recutils.php class.
My class simply launch system application with correct parameters.
But When I try to use recins with PHP's exec function, the command doesn't work will it work in command line.
This is the command that is executed by my script :
recins -f Title -v "Moi" -f Author -v "Moche" -f Location -v "loaned" -t Books ../database/books.rec
With PHP : Nothing, the record is not inserted (no error message at all too).
In terminal : OK, the command is well done and my record is inserted.
I also have a method to do a select operation using recsel and it works very well, will it use exactly the same file (and runs from exec too).
So, could someone explain me why the command don't work will another with the same file work ?
Thanks
PS : Further informations : http://www.gnu.org/software/recutils/
I would double check that you are running the command as the same user from the command line and your php script. That may be the problem. exec('whoami')
You said you had a script that starts your php script it should be the same user as that.
You might also want to running a simpler exec command to see if that will work first.
Other things to try:
Try checking stderr output exec('ls /tmp 2>&1', $out); This will redirect standard error to standard out so you get both.
Try using php's shell_exec() which will invoke a shell just like when you are running from the command line(eg. bash). shell_exec('ls /tmp 2>&1 >> /tmp/log') should even put all output into a log file.
I don't think this will help you but it is something to try if all else fails, set it as a background process and see if it completes. exec('nohup php process.php > process.out 2> process.err < /dev/null &'). The & will set the command to run in the background and let the script continue.
Good Luck
Is recins command accessible for PHP ? Also is path to books.rec correct ?
Try with absolute path.
In a previous post, I was trying to update the encoding for a download file from php. One of the suggestions was to run the unix2dos command before sending the file to the user. This works great when I run the command on the linux box, but when I try and run the command from php I get nothing. Here is what I tried:
$cmd = "unix2dos -n $fullPath $downloadFile";
echo exec($cmd, $out, $retVal);
This displays nothing to the screen, $retVal is 0, and $out is an empty string.
echo system($cmd, $retVal);
This displays nothing to the screen, $retVal is 0.
echo shell_exec($cmd);
This displays nothing to the screen.
I have also tried escaping the command and it parameters like:
$cmd = escapeshellcmd($cmd);
and
$cmd = "unix2dos ". escapeshellarg("-n \"$fullPath\" \"$downloadFile\"");
Please let me know if you see something that I am doing wrong.
Thanks!
Edit: Here is some info that may be helpful.
unix2dos version: 2.2 (1995.03.31)
php version 5.2.9
Running in apache 2 on in Redhat Enterprise Linux 4
Have you considered a pure PHP solution?
<?php
$unixfile = file_get_content('/location/of/file/');
$dosfile= str_replace("\n", "\r\n", $unixfile );
file_put_contents('/location/of/file/', $dosfile);
?>
Something like that should do it, although untested :)
Shadi
See which user the PHP exec command is running as:
<?php system('whoami'); ?>
If this command fails then you likely do not have permission to use exec() or system(), so check your INI files. But be sure to check the correct ones! On Debian systems there are separate Apache and CLI INI files stored at /etc/php5/apache/php.ini and /etc/php5/cli/php.ini respectively. Sorry I do not know the locations for RedHat.
If the whoami command succeeds, make sure that the unix2dos command can be run by the user that is shown, and that the same user is allowed to make changes to the files in question by using chmod or chown.
Are you using the full path to unix2dos? Perhaps the executable is in your path for your shell but not in the path that PHP is using.
My implementation of unix2dos produces no output. If the return value is 0 then the command succeeded and your file has been updated.
The only other thing I see is the -n option which my version doesn't seem to have. You should probably check your man page to see what options it supports
unix2dos does not display the file it converts. Therefor you must display it yourself. A very basic way to do it could be :
$cmd = "unix2dos -n $fullPath $downloadFile";
echo exec($cmd, $out, $retVal);
include "$fullPath."/".$downloadFile;
Using include is pretty dirty but quick and easy. A cleaner way would be to use fopen and read the file then display it.
You'd better create a function that enclose all the operation : conversion + display so you'll have everything at hands.
But, If I were you, I'd prefer to not use exec at all and use FileIterator with a trim on every line so you will not have to care about the carriage return nor deal with a hazardous shell binding.
Not sure about your exact problem, but debugging suggestion:
Try first setting $cmd to ls. See if that works. Then try using /bin/ls (use the full path.)
If those don't work, then there might be a problem with your PHP configuration - there might be a safemode parameter or something which disallows the use of exec(), shell_exec(), or system() functions.
I got the source code from here.
http://www.sfr-fresh.com/linux/misc/unix2dos-2.2.src.tar.gz
I compiled it and then ran the tool. This was my output:
rascher#danish:~/unix2dos$ ./a.out -n 1.txt 2.txt
unix2dos: converting file 1.txt to file 2.txt in DOS format ...
I think the problem is this: the program writes all of its output to stderr, rather than stdout. If you look at the source code, you can see "fprintf(stderr, ...)"
As far as I know, PHP will only read the part of your program's output that is sent to STDOUT. So to overcome this, it seems like you have to redirect the output of your program (unix2dos uses stderr) to stdout. To do this, try something like:
$cmd = "unix2dos -n $fullPath $downloadFile 2>&1"
The "2>" means "redirect stderr" and "&1" means "to stdout".
In either case, I would imagine that the file was converting properly, but since you weren't getting any of the expected output, you thought it was failing. Before making the change, check on the output file to see if it is in DOS or UNIX format.
The exec command doesn't work on my server, it does not do anything, I've had safe_mode off, and verified that all the console commands are working, I've tried with absolute paths. I've checked the permissions on the applications and all the applications I need have execution permissions. I don't know what else to do, here are the rundown of the codes I've tried.
echo exec('/usr/bin/whoami');
echo exec('whoami');
exec('whoami 2>&1',$output,$return_val);
if($return_val !== 0) {
echo 'Error<br>';
print_r($output);
}
exec('/usr/bin/whoami 2>&1',$output,$return_val);
if($return_val !== 0) {
echo 'Error<br>';
print_r($output);
}
The last two codes display:
Error
Array ( )
I've contacted the server service and they can't help me, they don't know why the exec command isn't working.
have a look at /etc/php.ini , there under:
; This directive allows you to disable certain functions for security reasons.
; It receives a comma-delimited list of function names. This directive is
; *NOT* affected by whether Safe Mode is turned On or Off.
; http://www.php.net/manual/en/ini.sect.safe-mode.php#ini.disable-functions
disable_functions =
make sure that exec is not listed like this:
disable_functions=exec
If so, remove it and restart the apache.
For easy debugging I usually like to execute the php file manually (Can request more errors without setting it in the main ini). to do so add the header:
#!/usr/bin/php
ini_set("display_errors", 1);
ini_set("track_errors", 1);
ini_set("html_errors", 1);
error_reporting(E_ALL);
to the beginning of the file, give it permissions using chmod +x myscript.php and execute it ./myscript.php. It's very heedful especially on a busy server that write a lot to the log file.
EDIT
Sounds like a permissions issue. Create a bash script that does something simple as echo "helo world" and try to run it. Make sure you have permissions for the file and for the folder containing the file. you chould just do chmod 755 just for testing.
A few more notes
For debugging always wrap your exec/shell_exec function in var_dump().
error_reporting(-1); should be on, as should be display_errors, as last resort even set_error_handler("var_dump"); - if only to see if PHP itself didn't invoke execvp or else.
Use 2>&1 (merge the shells STDERR to STDOUT stream) to see why an invocation fails.
For some cases you may need to wrap your command in an additional shell invocation:
// capture STDERR stream via standard shell
echo shell_exec("/bin/sh -c 'ffmpeg -opts 2>&1' ");
Else the log file redirect as advised by #Mike is the most recommendable approach.
Alternate between the various exec functions to uncover error messages otherwise. While they mostly do the same thing, the output return paths vary:
exec() → either returns the output as function result, or through the optional $output paramater.
Also provides a $return_var parameter, which contains the errno / exit code of the run application or shell. You might get:
ENOENT (2) - No such file
EIO (127) - IO error: file not found
// run command, conjoined stderr, output + error number
var_dump(exec("ffmpeg -h 2>&1", $output, $errno), $output, $errno));
shell_exec() → is what you want to run mostly for shell-style expressions.
Be sure to assign/print the return value with e.g. var_dump(shell_exec("..."));
`` inline backticks → are identical to shell_exec.
system() → is similar to exec, but always returns the output as function result (print it out!). Additionally allows to capture the result code.
passthru() → is another exec alternative, but always sends any STDOUT results to PHPs output buffer. Which oftentimes makes it the most fitting exec wrapper.
popen() or better proc_open() → allow to individually capture STDOUT and STDERR.
Most shell errors wind up in PHPs or Apaches error.log when not redirected. Check your syslog or Apache log if nothing yields useful error messages.
Most common issues
As mentioned by #Kuf: for outdated webhosting plans, you could still find safe_mode or disable_functions enabled. None of the PHP exec functions will work. (Best to find a better provider, else investigate "CGI" - but do not install your own PHP interpreter while unversed.)
Likewise can AppArmor / SELinux / Firejail sometimes be in place. Those limit each applications ability to spawn new processes.
The intended binary does not exist. Pretty much no webhost does have tools like ffmpeg preinstalled. You can't just run arbitrary shell commands without preparation. Some things need to be installed!
// Check if `ffmpeg` is actually there:
var_dump(shell_exec("which ffmpeg"));
The PATH is off. If you installed custom tools, you will need to ensure they're reachable. Using var_dump(shell_exec("ffmpeg -opts")) will search all common paths - or as Apache has been told/constrained (often just /bin:/usr/bin).
Check with print_r($_SERVER); what your PATH contains and if that covers the tool you wanted to run. Else you may need to adapt the server settings (/etc/apache2/envvars), or use full paths:
// run with absolute paths to binary
var_dump(shell_exec("/bin/sh -c '/usr/local/bin/ffmpeg -opts 2>&1'"));
This is somewhat subverting the shell concept. Personally I don't think this preferrable. It does make sense for security purposes though; moreover for utilizing a custom installation of course.
Permissions
In order to run a binary on BSD/Linux system, it needs to be made "executable". This is what chmod a+x ffmpeg does.
Furthermode the path to such custom binaries needs to be readable by the Apache user, which your PHP scripts run under.
More contemporary setups use PHPs builtin FPM mode (suexec+FastCGI), where your webhosting account equals what PHP runs with.
Test with SSH. It should go without saying, but before running commands through PHP, testing it in a real shell would be highly sensible. Probe with e.g. ldd ffmpeg if all lib dependencies are there, and if it works otherwise.
Use namei -m /Usr/local/bin/ffmpeg to probe the whole path, if unsure where any access permission issues might arise from.
Input values (GET, POST, FILE names, user data) that get passed as command arguments in exec strings need to be escaped with escapeshellarg().
$q = "escapeshellarg";
var_dump(shell_exec("echo {$q($_GET['text'])} | wc"));
Otherwise you'll get shell syntax errors easily; and probably exploit code installed later on...
Take care not to combine backticks with any of the *exec() functions:
$null = shell_exec(`wc file.txt`);
↑ ↑
Backticks would run the command, and leave shell_exec with the output of the already ran command. Use normal quotes for wrapping the command parameter.
Also check in a shell session how the intended program works with a different account:
sudo -u www-data gpg -k
Notably for PHP-FPM setups test with the according user id. www-data/apache are mostly just used by olden mod_php setups.
Many cmdline tools depend on some per-user configuration. This test will often reveal what's missing.
You cannot get output for background-run processes started with … & or nohup …. In such cases you definitely need to use a log file redirect exec("cmd > log.txt 2>&1 &");
On Windows
CMD invocations will not play nice with STDERR streams often.
Definitely try a Powershell script to run any CLI apps else, or use a command line like:
system("powershell -Command 'pandoc 2>&1'");
Use full paths, and prefer forward slashes always ("C:/Program Files/Whatevs/run.exe" with additional quotes if paths contain spaces).
Forward slashes work on Windows too, ever since they were introduced in MS-DOS 2.0
Figure out which service and SAM account IIS/Apache and PHP runs as. Verify it has execute permissions.
You can't run GUI apps usually. (Typical workaround is the taskscheduler or WMI invocations.)
PHP → Python, Perl
If you're invoking another scripting interpreter from PHP, then utilize any available debugging means in case of failures:
passthru("PYTHONDEBUG=2 python -vvv script.py 2>&1");
passthru("perl -w script.pl 2>&1");
passthru("ruby -wT1 script.rb 2>&1");
Or perhaps even run with any syntax -c check option first.
Since you are dropping out of the PHP context into the native shell, you are going to have a lot of issues debugging.
The best and most foolproof I have used in the past is writing the output of the script to a log file and tailing it during PHP execution.
<?php
shell_exec("filename > ~/debug.log 2>&1");
Then in a separate shell:
tail -200f ~/debug.log
When you execute your PHP script, your errors and output from your shell call will display in your debug.log file.
You can retreive the outputs and return code of the exec commands, thoses might contains informations that would explain the problem...
exec('my command', $output, $return);