Ravi Uday
Ravi Uday

Reputation: 1

Running exec in a script

I have this:

<?php
if ($_GET['run']) {
  # This code will run if ?run=true is set.
  exec("./check_sample.sh");
}
?

<!-- This link will add ?run=true to your URL, myfilename.php?run=true -->
<button type="button" onclick="?run=true">Click Me!</button>

The shell script check_sample.sh has some o/p which it prints using printf/echo When I click 'Click Me' I don't see those o/p. Also anypointer on how to make it take a text input and pass it as $1 arg. to script will also help

Upvotes: 0

Views: 122

Answers (3)

Orangepill
Orangepill

Reputation: 24645

exec will only give you the last line ... your probably want to use passthru

<?php
if ($_GET['run']) {
  # This code will run if ?run=true is set.
  passthru("./check_sample.sh");
}
?

For passing parameters you can just form the add it to the command like this. (escapeshellarg will handle the escaping and quoting of the value for you)

  passthru("./check_sample.sh ".escapeshellarg($_POST["fieldname"]));

If you need the output as a string your options are to use popen or surround the passthru in an output buffering block: ie:

 ob_start(); 
 /* passthru call */ 
 $data = ob_get_clean();

Upvotes: 1

TroyCheng
TroyCheng

Reputation: 571

exec() only catches the last line and it seems you'd better use a variable to catch it. see the manual. Other choices is system(), shell_exec(), passthru(), you can find which one is suitable via the PHP manual.

Upvotes: 0

jnrbsn
jnrbsn

Reputation: 2533

exec() doesn't output anything. You could use passthru().

Be VERY careful about passing user input to an external program. If you do make sure you escape it using escapeshellarg().

Kind of like this:

passthru('./check_sample.sh '.escapeshellarg($your_user_input));

Upvotes: 1

Related Questions