Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a shell command through PHP code?

Tags:

java

linux

php

I am trying to run a Jar file in the backend of my php code.But I am not getting the desired output to it.There is a jar file which runs in the background and returns the Page Rank of any of the keyword and Domain given to it. I am attaching the code,please suggest me any solution to it,because when I run it on the terminal,it is giving correct output.

Here is the Code :

    <?php
set_time_limit(0);
function returnJarPath()
{
    $jarPath = $_SERVER['DOCUMENT_ROOT'] . "myFolder/tools_new/includes/Rank.jar";
    return $jarPath;
}
$jar = returnJarPath();
$command = "java -jar $jar aspdotnet/microsoft.com";//Passing the Argument to the Jar file.


$shellOutput = shell_exec($command);
    print "The Shell Output is : " ; var_dump($shellOutput);print "<br />";
exec($command,$executeCommmand);
    print "The Exec returns the value : " ; var_dump($executeCommmand);print "<br />";
passthru($command,$passthruCommand);
    print "The Passthru returns the value : " . $passthruCommand. "<br />";
?>

I just checked apache's error log and the last error I found was :

sh: java: command not found

But as I have already said,I have been using the same command through SSH to run the Java command.So there's no such possibility of not having JAVA installed on the server.Please help me out of this mess...

like image 942
Nishant Shrivastava Avatar asked Sep 10 '10 12:09

Nishant Shrivastava


People also ask

What is PHP shell script?

PHP Shell or Shell PHP is a program or script written in PHP (Php Hypertext Preprocessor) which provides Linux Terminal (Shell is a much broader concept) in Browser. PHP Shell lets you to execute most of the shell commands in browser, but not all due to its limitations.

What is PHP command line?

PHP's Command Line Interface (CLI) allows you to execute PHP scripts when logged in to your server through SSH. ServerPilot installs multiple versions of PHP on your server so there are multiple PHP executables available to run.


1 Answers

If the jar file writes to standard output you can use exec.

Here is an example how I use it:

may be first: exec("cd jar dir"); // if jar fine needs to be executed from the same dir
$output = exec("/usr/bin/java -jar $jar aspdotnet/microsoft.com");

But as you say:

sh: java: command not found

It means the there is no path alias to java from php. Just use the full java path to the executable /usr/bin/java.

like image 52
darpet Avatar answered Sep 19 '22 20:09

darpet