I had create a cmd file:
phpunit Test.php > myTest.txt
It work when i run is directly. But when exec with PHP code:
exec("cmd.cmd");
a file myTest.txt created, but it blank
Most likely because phpUnit is not run when you call it via php (this could be due to security privileges).
Try
$output = '';
exec("cmd.cmd", $output);
echo $output;
And see what the execution actually returned, also you might need to specify a path since exec might run from the PHP execution path, not your PHP webroot where the file exists.
Related
I'm trying to run a Python script from PHP using the following command:
exec('/usr/bin/python2.7 /srv/http/assets/py/switch.py arg1 arg2');
However, PHP simply doesn't produce any output. Error reporting is set to E_ALL and display_errors is on.
Here's what I've tried:
I used python2, /usr/bin/python2 and python2.7 instead of /usr/bin/python2.7
I also used a relative path instead of an absolute path which didn't change anything either.
I tried using the commands exec, shell_exec, system.
However, if I run
if (exec('echo TEST') == 'TEST')
{
echo 'exec works!';
}
it works perfectly fine while shutdown now doesn't do anything.
PHP has the permissions to access and execute the file.
EDIT: Thanks to Alejandro, I was able to fix the problem. If you have the same problem, don't forget that your webserver probably/hopefully doesn't run as root. Try logging in as your webserver's user or a user with similar permissions and try to run the commands yourself.
Tested on Ubuntu Server 10.04. I hope it helps you also on Arch Linux.
In PHP use shell_exec function:
Execute command via shell and return the complete output as a string.
It returns the output from the executed command or NULL if an error
occurred or the command produces no output.
<?php
$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;
?>
Into Python file test.py, verify this text in first line: (see shebang explain):
#!/usr/bin/env python
If you have several versions of Python installed, /usr/bin/env will
ensure the interpreter used is the first one on your environment's
$PATH. The alternative would be to hardcode something like
#!/usr/bin/python; that's ok, but less flexible.
In Unix, an executable file that's meant to be interpreted can indicate
what interpreter to use by having a #! at the start of the first line,
followed by the interpreter (and any flags it may need).
If you're talking about other platforms, of course, this rule does not
apply (but that "shebang line" does no harm, and will help if you ever
copy that script to a platform with a Unix base, such as Linux,
Mac, etc).
This applies when you run it in Unix by making it executable
(chmod +x myscript.py) and then running it directly: ./myscript.py,
rather than just python myscript.py
To make executable a file on unix-type platforms:
chmod +x myscript.py
Also Python file must have correct privileges (execution for user www-data / apache if PHP script runs in browser or curl)
and/or must be "executable". Also all commands into .py file must have correct privileges.
Taken from php manual:
Just a quick reminder for those trying to use shell_exec on a
unix-type platform and can't seem to get it to work. PHP executes as
the web user on the system (generally www for Apache), so you need to
make sure that the web user has rights to whatever files or
directories that you are trying to use in the shell_exec command.
Other wise, it won't appear to be doing anything.
I recommend using passthru and handling the output buffer directly:
ob_start();
passthru('/usr/bin/python2.7 /srv/http/assets/py/switch.py arg1 arg2');
$output = ob_get_clean();
If you want to know the return status of the command and get the entire stdout output you can actually use exec:
$command = 'ls';
exec($command, $out, $status);
$out is an array of all lines. $status is the return status. Very useful for debugging.
If you also want to see the stderr output you can either play with proc_open or simply add 2>&1 to your $command. The latter is often sufficient to get things working and way faster to "implement".
To clarify which command to use based on the situation
exec() - Execute an external program
system() - Execute an external program and display the output
passthru() - Execute an external program and display raw output
Source: http://php.net/manual/en/function.exec.php
Alejandro nailed it, adding clarification to the exception (Ubuntu or Debian) - I don't have the rep to add to the answer itself:
sudoers file:
sudo visudo
exception added:
www-data ALL=(ALL) NOPASSWD: ALL
In my case I needed to create a new folder in the www directory called scripts. Within scripts I added a new file called test.py.
I then used sudo chown www-data:root scripts and sudo chown www-data:root test.py.
Then I went to the new scripts directory and used sudo chmod +x test.py.
My test.py file it looks like this. Note the different Python version:
#!/usr/bin/env python3.5
print("Hello World!")
From php I now do this:
$message = exec("/var/www/scripts/test.py 2>&1");
print_r($message);
And you should see: Hello World!
The above methods seem to be complex. Use my method as a reference.
I have these two files:
run.php
mkdir.py
Here, I've created an HTML page which contains a GO button. Whenever you press this button a new folder will be created in directory whose path you have mentioned.
run.php
<html>
<body>
<head>
<title>
run
</title>
</head>
<form method="post">
<input type="submit" value="GO" name="GO">
</form>
</body>
</html>
<?php
if(isset($_POST['GO']))
{
shell_exec("python /var/www/html/lab/mkdir.py");
echo"success";
}
?>
mkdir.py
#!/usr/bin/env python
import os
os.makedirs("thisfolder");
This is so trivial, but just wanted to help anyone who already followed along Alejandro's suggestion but encountered this error:
sh: blabla.py: command not found
If anyone encountered that error, then a little change needs to be made to the php file by Alejandro:
$command = escapeshellcmd('python blabla.py');
All the options above create new system process. Which is a performance nightmare.
For this purpose I stitched together PHP module with "transparent" calls to Python.
https://github.com/kirmorozov/runpy
It may be tricky to compile, but will save system processes and will let you keep Python runtime between PHP calls.
Inspired by Alejandro Quiroz:
<?php
$command = escapeshellcmd('python test.py');
$output = shell_exec($command);
echo $output;
?>
Need to add Python, and don't need the path.
I have a bash script, that I run like this via the command line:
./script.sh var1 var2
I am trying to execute the above command, after I call a certain php file.
What I have right now is:
$output = shell_exec("./script.sh var1 var2");
echo "<pre>$output</pre>";
But it doesn´t work. I tried it using exec and system too, but the script never got executed.
However when I try to run shell_exec("ls"); it does work and $output is a list of all files.
I am not sure whether this is because of a limitation of the VPS I am using or if the problem is somewhere else?
You probably need to chdir to the correct directory before calling the script. This way you can ensure what directory your script is "in" before calling the shell command.
$old_path = getcwd();
chdir('/my/path/');
$output = shell_exec('./script.sh var1 var2');
chdir($old_path);
Your shell_exec is executed by www-data user, from its directory.
You can try
putenv("PATH=/home/user/bin/:" .$_ENV["PATH"]."");
Where your script is located in /home/user/bin
Later on you can
$output = "<pre>".shell_exec("scriptname v1 v2")."</pre>";
echo $output;
To display the output of command. (Alternatively, without exporting path, try giving entire path of your script instead of just ./script.sh
Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.
(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.
On the terminal, I run this successfully within the web application's directory:
pdftohtml -c -noframes "documents/document1.pdf"
Now I want to do this through PHP, so I wrote a shell.sh file that looks like this:
sudo pdftohtml -c -noframes "documents/$file"
exit 0
Then I wrote this in php:
$output = shell_exec("file='document1.pdf' shell.sh");
It doesn't work, I expect to see html files generated, but I get some empty html files..since the command worked fine through the terminal, then I think the problem is in the way I execute it from php
echoing $output doesn't show anything.. what do I do wrong?
You need specify path to the script (or ./ if it is the current directory):
shell_exec("file='document1.pdf' ./shell.sh")
I would like to change the directory in Linux terminal from cli script, not the PHP current working directory -- hopefully with shell_exec().
Ex: from user#host:~$ to user#host:/the/other/directory$
system() and exec() are not allowed.
This isn't working in my case:
$dir = '/the/other/directory';
shell_exec('cd '.$dir);
nor these
shell_exec('cd '.escapeshellarg($dir));
shell_exec(escapeshellcmd('cd '.$dir));
pclose(popen('cd '.$dir));
But shell_exec('ls '.$dir) gives me the list in that directory. Any trickery?
When you're executing several commands like you are doing:
shell_exec('cd '.escapeshellarg($dir));
shell_exec(escapeshellcmd('cd '.$dir));
It won't work. The first command has nothing to do with the second one, so you can't use the results of the 1st command to execute the 2nd command.
If you want to execute a chain of commands, use the pipe symbol | like:
echo shell_exec("ls /etc/apache2 | grep fileName");
Local changes made by shell_exec only apply to that php process and therefore ls would fetch from that other directory. But when you exit the php, you are back to bash who never really cares what process does.
I doubt you can change bash's current directory from outside.
If you need to run bash in other directory, you could try this inside your php:
system('gnome-terminal --working-directtory=/home/doom');
this will start another terminal in new dir but script will wait till you quit this shell.
If you mean you want to change the parent shell's directory by calling a php cli script, then you can't do that. What you could do is at best:
shell> eval `your/cli/script`
and in your script do something like
<?php
...
echo "cd $dir"
?>