Looking for an easy explanation of exec in PHP - php

I am having trouble understanding the exec function in PHP. Can someone please explain it to me in simple terms?

exec — Executes command cmd in the system's command interpreter and returns the last line of output. Optional arguments allow the command output and return value to be captured.
string exec(cmd[, array_name][, $return_value]);
string cmd: Command to be executed

exec will call a program on the pc which runs your script and will return the last line of the output. e.g.
$result = exec('echo bla');
echo $result; // outputs 'bla'
(usually you don't want to use it, and some shared hosting servers do not allow it's usage due to security concerns)

i prefer shell_exec http://php.net/manual/en/function.shell-exec.php it returns all output

http://php.net/exec
(There seems little point in providing any other answer without a more specific question)

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)

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 system() help no simple commands work

I am trying to run a shell from one of my controllers in a PHP codeigniter applications,
I am trying to run the file /x/sh/xpay4.sh however I just get 127 returned to the screen, I can even use basic commands like ls or pwd can any suggest why this would be, I thought it might be safe_mode when I ini_get('safe_mode') it returns 1
system function is restricted in safe mode.
You can only execute executables
within the safe_mode_exec_dir. For
practical reasons it's currently not
allowed to have .. components in the
path to the executable.
escapeshellcmd() is executed on the
argument of this function.
http://www.php.net/manual/en/features.safe-mode.functions.php
system() returns only the last line of the shell output.
Sounds likt this is "127".
If you need the whole output instead, try:
$output = array();
exec('/x/sh/xpay4.sh', $output);
echo implode("<br>", $output);

Which function will you prefer to execute system commands with PHP?

like func("rm -rf /usr/local/)
Which 'func' will you use to do that?
It depends on what you want to obtain.
If you want to display the ouput of the command that has been executed, passthru does the trick :
This function should be used in place
of exec() or system() when the output
from the Unix command is binary data
which needs to be passed directly back
to the browser. A common use for this
is to execute something like the
pbmplus utilities that can output an
image stream directly.
If you want to get the output of the command in a variable as a whole string, you can use shell_exec (which is the same as using the backtick operator) :
Execute command via shell and return
the complete output as a string
And, if you want to get it line by line, you'll use exec :
If the output argument is present,
then the specified array will be
filled with every line of output from
the command. Trailing whitespace, such
as \n, is not included in this array.
And, finally, if you need a bit more control, you'll use proc_open -- see the documentation, about that one ; it's a bit more tricky, I guess.
Still, when using those :
Don't forget you are calling a program that has to be available on the host machine
This means if you are using a Linux command, your application will most likely not work on windows
Depending on the configuration of PHP, it is possible that only a couple of commands could be available ; see safe_mode_exec_dir, about that
Using this means launching another processus -- probably not that good for performances
So, I'd use those only when it is really necessary.
You would use PHP's exec function. Other options include system, passthru, and the backtick operator.
Personally I think proc_open is the best approach.
http://php.net/proc_open
This gives you far more control over input, output and let's you check it's exit status and STDOUT, which is more than most other commands for system calls. It also doesn't hold up the system while the command exits.

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