Cant get php exec to work - php

I've been fighting with this for a few hours now, and I can't seem to work it out.
tried exec(), shell_exec(), and system(). Nothing works.
I have this:
exec("/usr/bin/php /var/www/vhosts/domain.com/httpdocs/shell/send.php >> /var/www/vhosts/domain.com/httpdocs/shell/paging.log &");
send.php simply has:
echo 'works';
But nothing shows up in the log. I've googled and read stuff on here, but I can't find anything to help.
I'm running php v.5.3.8.
safe mode is on
I'm pretty sure that is the path to php, but can't really find out how to find it, so I'm going on phpinfo().
exec('whoami'); does nothing. Is it suppose to show in the browser? or email you something?
any ideas?

According to PHP Manual for exec function:
When safe mode is enabled, you can only execute files within the
safe_mode_exec_dir. For practical reasons, it is currently not allowed
to have .. components in the path to the executable.
Check http://php.net/manual/en/ini.sect.safe-mode.php#ini.safe-mode-exec-dir
Also, be aware that the web server user must have permission to write in the log file.
EDIT: To turn safe mode off, check not only php.ini file but also virtual hosts specific configurations in your web server, whether it is Apache, NginX or other. If you use Plesk, look in vhosts for httpd.include, and make sure that safe_mode is set to off there as well.

> The last line from the result of the command. If you need to execute
> a command and have all the data from the command passed directly back
> without any interference, use the passthru() function. To get the output
> of the executed command, be sure to set and use the output parameter.
I am not looking for output, and the last two arguments of exec() are optional. I my case what I really need is to be able to open a folder on the desktop. This exact syntax worked very well in MAMP_PRO_1.9.6, but no longer works in MAMP_PRO_2.0.5 (it's broken)
<?php
exec("open /path/to/any/folder"); // BROKEN in Mamp Pro 2.0.5
?>

To get the output, you need to pass a second parameter, or you can get the last line of output by echo'ing it.
From the PHP manual:
string exec ( string $command [, array &$output [, int &$return_var ]] )
Return Values:
The last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.
To get the output of the executed command, be sure to set and use the output parameter.

Related

Passing variables from PHP to python

I have a python script. When I run the script from the command line as:
python upgrade.py arg1 arg2
The script runs successfully.
Now I am trying to pass the same variables via PHP code using:
passthru("python upgrade_device.py $arg1 $arg2");
The script does not execute.
I am accepting the arguments using:
sys.argv
The arguments are passed correctly
I have tested using print
This is specific command where the execution fails:
child=pexpect.spawn('ssh admin#%s'%ip_addr)
ip_addr is one of the arguments passed from PHP. Right below this command I am ip_addr so as to find what value is passed to the command. and the value is as expected.
I have the ip_addr variable stored correctly.
I have even type casted it to string so that should not be problem.
In general, is there a difference of format in passing variables from the command line and passing from PHP
For my understanding i think passing it through shell and php is the same, i can't be sure for 100% but that what i know from experience.
For your case if you have verified with print that it's the right string to pass (mean take the output and test it in the terminal if it work) if it work, than verify if the python script file is in the same directory as the php script file, because the shell will be opened at the current php script path. And so the shell command should respect that. For example let assume php script file is in the root "/", and python script file is in "/myPythonScripts/imageProccessing/" then when you execute something like "python myPyScript.py 646545645" for example, in this example in php you should execut "python ./myPythonScripts/imageProccessing/myPyScript.py 646545645", as i said the shell is launched on the php script path.
Now if that's not the problem, then try escaping the string first, with escapeshellcmd(). And see what it give. There is characters that are not supported by the shell, or that have a certain signification and parsed by the shell differently. make sure none of them is passed as argument.
In case none of the above is helpful try to use execshell() instead, and see what it give. Too probable that will not make a difference.
Edit: In case nothing helped, try to change just a bit the way of the exchange is done, and use the way it's done in this response using json https://stackoverflow.com/a/14048046/7668448 (it's a kind of more convenient)
Please if any of that solved the problem, precise in a response which one was! I hope it will help. Also if it's not your case it may be useful for other persons in the future. Think also about giving the solution when you do! (i also personally interested too)

Launching code from CMD works, but not through a PHP exec script... why is this?

When I login to Windows Server 2008 and run this code using cmd.exe (as an Admin), it works:
php -f e:\path\to\file\file-name.php go 4001
However, when I try to launch this from a php file, it does not:
$cmd = escapeshellarg("php -f e:\path\to\file\file-name.php go 4001");
exec($cmd);
exit;
I've been at it for 6 hours and can't find a solution. I've even tried pstools to enable access to psexec, still no luck. I can't even get psexec to work from the command line because it seems that I'm unable to pass variables through (go and 4001).
Update
When I run the code using the PHP file, nothing happens, the file I want to be created does not get created and I'm not sure how to throw errors through this method.
<?php
if(function_exists('exec')) {
echo "exec is enabled";
}
?>
Outputs, exec is enabled.
Please help!
I'm receiving no errors or warnings of any kind.
Well, you have this:
exec($cmd);
And the function signature is this:
string exec ( string $command [, array &$output [, int &$return_var ]] )
Change your code to make use of the optional arguments that provide error info.
In any case, you're encoding your complete command as a single argument. That cannot work: I count 5 different tokens in your command line, not one. You must encode all 5 items separately and you need to use different functions for commands and arguments.
Additionally, escapeshellarg() is basically a Unix-only function that has been poorly patched so it doesn't have obvious security issues on Windows, but it doesn't work properly on Windows, it'll often strip characters rather than escaping. I found a nicer replacement at the Symfony framework which is rather easy to adapt for standalone use.

Why won't shell_exec execute files but does execute simple commands?

Is there any reason why I can not complied files in PHP's shell_exec/exec/system function?
Example of something that does work in command line and PHP's shell_exec function:
<?php
$data = shell_exec("ls");
echo $data;
?>
Example of something that does not work in PHP's shell_exec function but will work in command line (I can confirm that):
<?php
$data = shell_exec("./c-compiled-file argv1 argv2 argv3");
echo $data;
?>
Is there anything I can do on my server so this will work? I've looked everywhere and no solutions I found fixed the problem. The compiled file is in the same directory as the PHP script as well, it just won't execute it. Also if you're asking, yes I have tried this with SSH2 and it still will not execute.
Also PHP is not in safe mode and NO functions are disabled.
Some common glitches when executing external commands from PHP that work fine from shell:
Command uses relative paths but PHP is launched from an arbitrary location:
Use getcwd() / chdir() to get/set working directory
PHP and shell run with different user credentials. This is often the case when PHP runs through a web server.
PHP and shell run different commands. Many people call stuff like exec("foo $bar") and doesn't even check what "foo $bar" contains.
No error checking is done. The bare minimum is to capture and print standard output, standard error, status code and, of course, all PHP error messages including warnings and notices.
You can redirect stderr to sdtout
You can use a PHP function that allows to capture more information, such as exec()
The web server is disallowed to execute the command at operating system level.
Lookout for SELinux or similar tools.
Just a guess, but the binary you're trying to execute might not have the proper permissions. Prepeding it with ./ in the command line forces it to execute, but PHP probably strips that for security purposes. Try this:
chmod +x c-compiled-file
You want to use system in the second case, and not shell_exec.
system executes an external program and displays the output.
shell_exec executes a command via shell and returns the complete output as a string.
and for good measure:
exec simply executes an external program.
Furthermore you want to make sure your external program is executable and (though you have stated it, I'll restate this) has execute permissions for the user which is running the web server. You also want to make sure the directory your external program is running in has the ability to write to its directory or /tmp or whatever output directory you have set.
Finally you should always use absolute paths for executing things like this in cron or php or whatever... so don't use ./c-compiled-file argv1 argv2 argv3, but instead use /home/username/c-compiled-file argv1 argv2 argv3 or whatever the full path is.

php exec() is not executing the command

I have tried to use exec() with 'whoami' to check if it works and I got the result of
nt authority\system
Now I need to run a .exe file with parameters from php via exec() function.
I tried this in command prompt and it actually runs the program with given parameters. This is the example command.
NOTE the exe file gets 3 inputs (folder, file_name, report_file_nmae)
> ..\..\some_file.exe folder="C:\path_to_folder" param=1.xml report=2.xml
But when I run this command from php file:
exec('..\..\some_file.exe folder="C:\path_to_folder" param=1.xml report=2.xml');
nothing is happening. This is the first time I am using exec() function, so I am not familiar with its details. What is wrong?
I tried using:
\\ instead of \
escapeshellarg() on the directory
added "" around directory folder names
No luck
Addendum:
echo exec($command) // echos < .... why?
or
exec($command, $output);
print_r($output); // Array()
I even changed the permission on the file to full control to all users.
If I call the program from command prompt, I can see the icon appearing next to clock for a second.
But the same call from php will not even call the program.
Edit
Even exec('notepad.exe'); is not working. Something has to be done with php configurations maybe?
I already said that I was new to exec() function. After doing some more digging, I came upon 2>&1 which needs to be added at the end of command in exec().
Thanks #mattosmat for pointing it out in the comments too. I did not try this at once because you said it is a Linux command, I am on Windows.
So, what I have discovered, the command is actually executing in the back-end. That is why I could not see it actually running, which I was expecting to happen.
For all of you, who had similar problem, my advise is to use that command. It will point out all the errors and also tell you info/details about execution.
exec('some_command 2>&1', $output);
print_r($output); // to see the response to your command
Thanks for all the help guys, I appreciate it ;)
You might also try giving the full path to the binary you're trying to run. That solved my problem when trying to use ImageMagick.

PHP #exec is failing silently

This is driving me crazy. I'm trying to execute a command line statement on a windows box for my PHP web app. It's running on windows XP, IIS5.1. The web app is running fine, but I cannot get #exec() to work with a specific contactenated variable. My command construction looks like this:
$cmd = ($config->svn." cat ".$this->repConfig->svnParams().quote($path).' -r '.$rev.' > '.quote($filename));
This command does not work as is above, when it generates the following string:
svn --non-interactive --config-dir /tmp cat "file:///c:/temp/test/acccount/dbo_sproctest.sql" -r 1 > "C:\Inetpub\sites\websvn\temp\wsv5B45.tmp"
If I copy/paste this to my own command line, it works fine.
If I hard code that very same path instead of adding it with the variable, it works! I've tried with and without quotes around the file name. I've tried with and without quotes around the entire command. I've tried other directories. I've tried passing an output paramter to exec(), and it comes back empty (Array () ). I've tried redirecting the output of the error stream of the command to a file, and that error output file never gets created.
The only thing I can possibly concieve of is that exec() is failing silently. What on earth am I doing wrong here? If I hard code the file path, using the same dir structure and filename, it works fine. If I don't, it doesn't.
Maybe the slashes () in the file path aren't being escaped properly, but when I do it manually with single quotes they are not considered escape sequences??
UPDATE:
I took the # off of exec, and still not seeing any errors.
I gave the full path to SVN, still no luck. It should be noted that the command worked fine before with the non-full path SVN so long as I manually specify the file destination for cat.
Update 2: RE: Kieth
I'm calling exec by trying both:
exec($cmd);
or
exec($cmd, $out);
My php.ini already had safe_mode = 0.
I added error_reporting(E_ALL); and didn't see anything new
If I echo (or print_r) my exec call, I am not actually seing anything
If I echo (or print_r) my exec call when included an output var, I get an empty arr
Update 3
I tried both escapeshellcmd and escapeshellarg to no avail (good idea though).
I should add that the file is being created through invoking
tempnam("temp", "wbsn");
The fact that it works just fine if I manually specify the string instead of letting it be generated by tempname seems to suggests that the source of the problem, but I can't figure out how. I did a comparison of the manual string with the one generated, and it came back as a match.
#exec will always fail silently, because # is PHP's error suppression operator.
Not sure if this will help you since you're on Windows and I'm on Linux, but I ran into this same problem of silent errors from PHP exec(). I figured out that the command I was attempting to issue (nconvert) sends its error messages to the standard error stream, not standard out. So I added
2>&1
at the end of the command line to redirect my error back to the standard stream. Then I could see that nconvert was giving me a permission denied error.
It could be that the PATH isn't the same from your php script vs your user account. Try removing the # and see if it's trying to throw an error.
In addition, you may want to try putting the full filesystem path to the SVN executable.
Well, if removing # isn't working, try including this at the start of the piece of code you're running:
error_reporting(E_ALL);
That'll turn on full error reporting, just in case you have it turned down or disabled in your php.ini file.
I don't suppose you could show us how exactly you're calling exec()? Could you also check to make sure you're not accidentally running the script in safe mode? Are you echoing out what exec() is returning, and if so, what is it returning?
I'm not a big fan of adding another response, but if I just edit my previous response, you may not see it.
PHP has some special escaping commands for shell scripts: escapeshellcmd and escapeshellarg.
I think you should be able to use escapeshellcmd around your entire $cmd, but I'm not sure.
Have you tried echo exec("dir") or something simple to see if exec() is working at all?
I don't know what going on, but I at least have a workaround.
This works:
$tmp = tempnam("./", "wbsn");
$filename = dirname($tmp).'\\temp\\'.basename($tmp);
This, however, does not, but I would have expected it to generate the same path (diff file name since it's a new tempnam()).
$tmp = tempnam("temp", "wbsn");
Also, this does not work, which I also would expect to generate the same thing:
$tmp = tempnam("temp", "wbsn");
$filename = dirname($tmp).'\\'.basename($tmp);
All 3 of these solutions appear to generate the same file paths, but only the first one actually works when used in my exec. I have no clue why it does not.
Visual inspection (echo) of all 3 of these appear to generate the same paths (with the exception of filenames differing, of course). A string comparison of dirname() of each of these 3 shows as a match. I have no clue what the deal is, but the first one is a workaround.
A very useful trick when debugging shell exec problems is to place an "echo" at the beginning of the command. Make sure that you can view the standard output somewhere.
This will let you examine the command for any obvious problems. Perhaps it has a wildcard that is expanding unexpectedly, or perhaps the shell quoting is not exactly right. The echo will let you see this, and you can cut and paste the echoed command into another shell to see if it is working properly.
My advice will be to switch from WIN, IIS to linux, but as alternative you can try this:
function exec_alt($cmd) {
exec($cmd, $output);
if (!$output) {
/**
* FIXME: for some reason exec() returns empty output array #mine,'s machine.
* Somehow proc_open() approach (below) works, but doesn't work at
* test machines - same empty output with both pipes and temporary
* files (not we bypass shell wrapper). So use it as a fallback.
*/
$output = array();
$handle = proc_open($cmd, array(1 => array('pipe', 'w')), $pipes, null, null, array('bypass_shell' => true));
if (is_resource($handle)) {
$output = explode("\n", stream_get_contents($pipes[1]));
fclose($pipes[1]);
proc_close($handle);
}
}
return $output; }

Categories