I use the testing framework DalekJS to test the user interface. To execute my testing script mytest.js I type into the shell:
cd /Applications/XAMPP/xamppfiles/htdocs/tests
dalek mytest.js
and it works fine. Now I would like to execute the same script with PHP. My code:
<?php
chdir('/Applications/XAMPP/xamppfiles/htdocs/tests');
$command = 'dalek mytest.js';
exec($command, $return, $return_var);
var_dump($return);
var_dump($return_var);
Running my PHP-script in browser, it prints:
array(0) { } int(127)
The DalekJS script generates a screenshot when executing in shell but running with PHP it does not happen anything. I have also tried shell_exec(), system() and passthru() without success.
Do you have any idea why the PHP script does not work?
Calling dalek from PHP works fine for me. Is it possible your PHP process is running with a different environment (containing PATH, amongst other things) that your user? Maybe the apache user or some such?
<?php
// change current working directory of the current PHP process,
// this will subsequently change the initial CWD of exec()
$whereMyTestsAre = __DIR__;
chdir($whereMyTestsAre);
// locate dalek
$dalek = exec('which dalek');
// abort if there is no dalek,
// you may want to check PATH or supply the full path yourself
if (!$dalek) {
echo "could not find dalek executable, please check your path";
$PATH = exec('echo $PATH');
echo '$PATH is ', $PATH, "\n";
exit(1);
}
// relative to $whereMyTestsAre
// exec() blocks until the child process (dalek) exits
exec('dalek mytest.js');
Related
So i have a project where I send spotify track URL to server and store it. I use laragon with PHP 7.4 installed, windows 11. I use that downloader. It works via cmd command line. When I try to use it by hand it works fine, but when i send it by exec() it doesn't work. I can't get any return message neither. I have tried using exec(), system() and shell_exec() functions. The problem might be with with system variables, as these might not be visible for PHP. I have also tried turning on/off server and it didn't work. I have also tried to put putenv('PATH=' . $_SERVER['PATH']) at the beginning of file. I tried to check laragon path variables itself - I couldn't see these i have added. Any other default windows commands works as should be. Any ideas on how to fix it?
Here is my PHP code:
function createFile($url, $token){
function execCommand($dir, $url){
$command1 = "cd $dir";
$command2 = "spotdl $url";
if(!shell_exec($command1. "&& ". $command2)) return false;
return true;
}
$path = "C:\Laragon/laragon/www/temp/";
$dir = $path.$token.'/';
if(!mkdir($dir, 0777)) throwError("Server error");
if(!execCommand($dir, $url)) return false;
return true;
}
I know i'm not returning any output from console, but that is post updates. Second command is definitely beeing called, i have tested it on some other commands (like mkdir)
In many os the errors output (stderr) of the commands isn't the same that the normal output (stdout), you need to redirect the errors to the stdout. so the command must be:
$ command $arg1 $arg2 ... 2>&1
This cause that the errors messages will be sent to the stdout, Is util remember this when you are working with system calls.
Now in your code i prefer to use the exec function in php
<?php
$result = 0;
$output = [];
$command = "your command with the 2>&1";
exec($command, $output, $result);
if ($result != 0) {
// here an error ocurred and you can see the error on the ouput array
exit();
}
// here you know that the command was executed successfully
After re-installing laragon it worked. I Have checked before uninstalling path variables and i haven't seen mine that should be in.
I couldn't modify it either so I just reinstalled it.
I have a PHP script that calls a Python script (with arguments):
<?php
$UPLOAD_DIR = 'tmp';
$AUDIOSPLIT = "../audiotranscri/scripts/audiospliter.py";
// This also fails using a symlink in the same dir
//$AUDIOSPLIT = "spliter";
$media_path = "tmp/media.mp3";
$subtitles_path = "tmp/mediasub.ass";
$cmd = "python3 ".$AUDIOSPLIT." ".$media_path." ".$subtitles_path." ".$UPLOAD_DIR;
echo($cmd);
system($cmd,$returnv);
echo($returnv);
?>
It works when i run this from a bash terminal
$ php7.2 dummy.php
But fails when call it from a website (Apache2 with PHP). Why ?
N.B: I am sure Apache and PHP are running OK since phpinfo() works perfectly. Versions are PHP 7.2.15, ubuntu 18.04.1, Apache 2.4.29.
Consider trying one of these:
use full path for your program as PATH might not be set when using system() - change "python3 " to "/usr/bin/python3 ", or wherever your python3 is.
Using another function, exec(), shell_exec(), passthrough()
Check if your web server allows you to run given functions when running through http, check in your php.ini, or check with php script accessed through http
<?php
$function_name = "system";
if ( function_exists($function_name) ) {
echo "$function_name is enabled";
}
else {
echo "$function_name is not enabled";
}
I have a PHP script that is run via CLI. In turn I want that script to call a bash script, but preferably I would like to break up the BASH requests so I can see the action as it is happening.
I can seem to set Environmental variables and they seem to exist between shell_exec() functions. But even when I have a source file like:
source ./bashes/functions.sh
And in the source file I use "export -f function-name" to export the functions in the script before executing the next line, the next line does not see the functions.
$file = file('./bashes/bash_testing.sh',FILE_SKIP_EMPTY_LINES);
//we want to watch this in realtime so write each line seperately to shell.
foreach($file as $command) {
$output->writeln(shell_exec($command));
}
The function $output->writeln is a helper function just to echo the returned result. But basically the error I get is
sh: now: command not found
now is defined as a function in the included bash_testing.sh shell script.
Anyone know how I can resolve this issue?
Here is the source to the ./bashes/functions.sh file:
function now {
date -u +%T
}
export -fx now
There is a way to maintain a single bash shell, execute commands and handle the return. I recently published a project that allows PHP to obtain and interact with a real Bash shell. Get it here: https://github.com/merlinthemagic/MTS
I would suggest not triggering a bash script but rather trigger the induvidual commands. That way you can handle the return and not have to build exception handling in bash.
After downloading you would simply use the following code:
//get a real bash shell.
$shell = \MTS\Factories::getDevices()->getLocalHost()->getShell('bash', false);
$return1 = $shell->exeCmd($command1);
//logic to handle the return
$return2 = $shell->exeCmd($command2);
//logic to handle the return
..... etc
I need to run a python script (a log parser) on hundreds of log files, but I'm a PHP guy so I figured I'd write a little PHP script to grab the list of files from a directory and call the python script dynamically in a foreach loop.
I've set variables in my PHP script using the full system paths to the python binary, the full path to the python script and checked that everything seems correct. I echo the output of the script I'm trying to run to check it over:
<?php
// batch.php (modified for SO post)
$python = '/usr/bin/python';
$script = '/mnt/data/scripts/the/python/script.py';
// $folder contains the full system path to the dir containing
// the files I need to pass as args to script.py
$files = scandir($folder);
foreach($files as $file){
if($file=='..'||$file=='.')
{
continue;
}
$system = $python.' '.$script.' '.$folder.$file.' 2>&1';
echo "Running ". $system ."\n";
// I also tried passthru( )
system($system);
}
Next I do
php batch.php
All I get is the first line from PHP:
Running /usr/bin/python /mnt/data/scripts/the/python/script.py /path/to/data/file/one.log
I can copy, paste and run the output echoed in shell (after 'Running ') directly with python and there's my output, no problem, so I know the PHP script has no syntax problems.
But when running the php script wrapping it, it produces no output other than my echo( ) statement from PHP. It just hangs there (I am thinking that my long-running Python script is actually working, but I'm not sure how to tell.) There's nothing in the error log, and the script never exits until I Ctrl-C.
I've seen a lot of discussions about exec( ), system( ) and passthru( ) and from what I can tell I should be seeing output using system( ) but for some reason I'm not.
I even tried to
root:~# ps aux | grep php
and then
root:~# strace -p <process_id>
of the PHP script, but all I get is
root:~# strace -p 14232
Process 14232 attached - interrupt to quit
read(4,
Note: I added the 2>&1 bit from this question but it didn't help; that references Apache however I'm running PHP on the CLI.
Note:
root:~# echo $PYTHONPATH
in shell produces no output.
What am I missing?
python buffers output by default. If your script terminates prematurely (possibly thanks to a PHP script timeout), the buffer is not flushed.
Call set_time_limit() to extend the timeout, and set environment variable PYTHONUNBUFFERED to a nonempty string, or run python with -u.
I am trying to call a simple python script
#!/usr/local/python25/bin/python
print "hello world"
from the following php script
<?php
echo exec("/usr/local/python25/bin/python myfile.py");
?>
But nothing was happened.
Please tell me what is wrong here? (I also checked other thread but I could not solve my problem)
Question Solved:
I forgot to give the permission to access /usr/local/python25/bin/python. After I did this, the problem solved.
Thank you so much for your help!
1.The exec function just return the last line from the result of the command.
2. The print statement in python (except python 3) automatically adds a newline at the end.
This is the reason you feel nothing was happened.
You can catch the whole output by this way.
exec("/usr/local/python25/bin/python myfile.py 2>&1", $output);
print_r($output);
Kind of an obvious point here, but can you run the python script from a terminal? Does it actually run?
Make sure the script is executable by whatever user PHP is running as - chmod 777 myfile.py, and just to be safe chmod 777 /usr/local/python25/bin/python. Also, make sure the python script is in the same directory as the PHP script, which is what your method of calling it requires.
Try changing your PHP script to this, and tell me what you see: (EDITED)
<?php
// Path to the python script - either FULL path or relative to PHP script
$pythonScript = 'myfile.py';
// Path to python executable - either FULL path or relative to PHP script
$pythonExec = '/usr/local/python25/bin/python';
// Check the file exists and PHP has permission to execute it
clearstatcache();
if (!file_exists($pythonExec)) {
exit("The python executable '$pythonExec' does not exist!");
}
if (!is_executable($pythonExec)) {
exit(("The python executable '$pythonExec' is not executable!"));
}
if (!file_exists($pythonScript)) {
exit("The python script file '$pythonScript' does not exist!");
}
// Execute it, and redirect STDERR to STDOUT so we can see error messages as well
exec("$pythonExec \"$pythonScript\" 2>&1", $output);
// Show the output of the script
print_r($output);
?>
If you want to capture the subprocess' stdout, you should use passthru
Also you don't need the first line of that python script if you're calling the python interpreter directly.