How to execute C code through PHP by prompting terminal - php

I have a C code that I have to execute through PHP,
I have used exec('./sys'), sys is my executable file.
I have also tried system(), passthrough(), shell_exec() and they are not giving output.
When I executed exec('who'); it gives the output.
What can I do to execute sys?

Each of those methods you reference will execute your sys file, but you need to make sure you are executing the correct path. Your working path is determined by what script is actually executing PHP. For example, if you're executing your code through apache or the command line your working directory may be different. Lets assume this file structure:
+ src/
| + script.php
| + sys
I would recommend using PHP's __DIR__ magic variable in your script.php to always reference the current file's directory, and then work from there:
// script.php
exec(__DIR__ . "/sys");
Retrieving output can be done a couple different ways. If you want to store the output of the script in a variable, I would recommend using exec according the the manual:
Parameters ΒΆ
command
The command that will be executed.
output
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. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().
return_var
If the return_var argument is present along with the output argument, then the return status of the executed command will be written to this variable.
exec will return the first line of output, but if you want more than that you need to pass a variable by reference:
// script.php
$output = array();
exec(__DIR__ . "/sys", $output);
$output will then contain an array of each line of output from the command. However if you want to run your sys script and directly pass through the output then use passthru(__DIR__ . "/sys"); For example, if you wanted to execute a command that required input on the command line, passthru would be the best option.

Related

PHP exec() Output Cut Short

I have a PHP file that runs a node script using exec() to gather the output, like so:
$test = exec("/usr/local/bin/node /home/user/www/bin/start.js --url=https://www.example.com/");
echo $test;
It outputs a JSON string of data tied to the website in the --url paramater. It works great, but sometimes the output string is cut short.
When I run the command in the exec() script directly, I get the full output, as expected.
Why would this be? I've also tried running shell_exec() instead, but the same things happens with the output being cut short.
Is there a setting in php.ini or somewhere else to increase the size of output strings?
It appears the only way to get this working is by passing exec() to a temp file, like this:
exec("/usr/local/bin/node /home/user/www/bin/start.js --url=https://www.example.com/ > /home/user/www/uploads/json.txt");
$json = file_get_contents('/home/user/www/uploads/json.txt');
echo $json;
I would prefer to have the direct output and tried increasing output_buffering in php.ini with no change (output still gets cut off).
Definitely open to other ideas to avoid the temp file, but could also live with this and just unlink() the file on each run.
exec() only returns the last line of the output of the command you pass to it. Per the section marked Return Value of the following documentation:
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.
https://www.php.net/manual/en/function.exec.php
To do what you are trying to do, you need to pass the function an array to store the output, like so:
exec("/usr/local/bin/node /home/user/www/bin/start.js --url=https://www.example.com/", $output);
echo implode("\n", $output);

PHP exec() execute last command only?

Here is an example trying to understand exec() function
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
echo exec("id;ls");
?>
When i run this code the result of ls only
Does exec() execute the last command only or it executes both of them and echo the last command ?
You can use shell_exec() instead for this purpose.
On the other hand, exec() returns only last line of the output (by default), but you can provide reference for output array as a second argument.
See the documentation for more info.
exec returns the last line from the result of the command. You have to use output argument. If the output argument is present, then the specified array will be filled with every line of output from the command.
exec("id;ls", $output);
var_dump($output);
you need write a shell script for Linux(excutable with .sh file)

PHP system() keeps echo even though

So I need to found out if an upload from a user is images/ video and what type. I currently use
"filetype"=>system("file -i -b ".$_FILES['file']['tmp_name'])
which is inserted into my MongoDB collection via this
$s3file='http://'.$bucket.'.s3.amazonaws.com/'.$actual_image_name;
$collection = static::db()->media;
$datetime = time();
$mediaupload = array("owner"=>$_SESSION['user_information'][0]['_id'],"filelink"=>$s3file,"filetype"=>system("file -i -b ".$_FILES['file']['tmp_name']),"filesize"=>$size,"uploadtime"=>$datetime,"ownerid"=>$_SESSION["user_information"][0]['_id']);
$collection->insert($mediaupload);
$media = $collection->findOne($mediaupload);
However what I am noticing is it echos the result out to the PHP page - which is not what I need it to do. i know it is the system function because when I remove that function it does not echo the uploaded file type to the php code.
I am wondering therefor how can i still run that system file -i -b function and get it to include into the MongoDB database but not echo the result into the public php page return.
Try something like (for multi-line output)
exec("file -i -b ".$_FILES['file']['tmp_name'], $output);
array("filetype"=>$output);
It may look a little unorthodox, but exec uses its second input parameter as a way to pass the output information back to you - the output of file will be stored as an array into $output.
From the docs:
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. Note that if
the array already contains some elements, exec() will append to the
end of the array. If you do not want the function to append elements,
call unset() on the array before passing it to exec().
If you simply want the first line from the output, use the simpler version:
array("filetype"=>exec("file -i -b ".$_FILES['file']['tmp_name']));
I have switched the system to exec() and that seems to of fixed my issue

return value from php to batch file

I have a batch file that calls a php script. The php script returns a value that I want to use in the batch script. The php script echoes the correct return value however I have not been able to find a way to capture the value to use in the batch file.
I have tried a number of variations on for loops without success. My batch script is as follows:
#echo off
Setlocal
"C:\Program Files (x86)\PHP\v5.3\php.exe" -f C:\inetpub\wwwroot\hello.php
endlocal
This of course just returns "Hello." How can I set a variable in the batch file (a variable named retVar for example) to contain what is returned from this php call?
thank you,
Shimon
#echo off
setlocal enableextensions
for /f "delims=" %%a in (
'"C:\Program Files (x86)\PHP\v5.3\php.exe" -f C:\inetpub\wwwroot\hello.php'
) do set "retVar=%%a"
echo %retVar%
Use for /f to execute a command (in the in clause) and for each line in the command output, execute a block of code (in the do clase). For each line, the variable/replaceable parameter (%%a in sample code) will hold the line. In this case, as the output of the php command is only one line, it will be executed only one time, storing the php output line into the retVar variable.
for /f will, by default, try to tokenize the lines it reads, splitting in fields using spaces a delimiters. To avoid this behaviour, a empty list of delimiters is used, so all the line contents will be stored in %%a

How to run Java program and get output in PHP?

I'd like to run something like (in myProgram.sh):
java -cp whatever.jar com.my.program $1
within PHP and read the output.
So far I have something like:
$processOrderCommand = 'bash -c "exec nohup setsid /myProgram.sh ' . $arg1 . ' > /dev/null 2>&1 &"';
exec($processOrderCommand);
But what I'd really like is to be able to get the output of the java program within the PHP script and not just execute it as another thread.
How can this be done?
You can do this :
exec($processOrderCommand, $output);
From the documentation :
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. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().
For a better control on your execution you can take a look at proc_open()
Resources :
php.net - exec()
php.net - proc_open()
The key is that the classpaths need to be absolute within the shell_exec
PHP script.
Or at least that's the only way I could get it to correctly work. Basically it's almost impossible to tell from environment to environment what the relative directory is that the php script is running the JVM.
As well, it helped to put the absolute path location for java, such as usr/.../bin/java

Categories