4

I'm trying to execute a linux command through a PHP command-line script, which is no problem using the exec command.

The problem is, the command I am executing (mysqldump) outputs an error message if something is wrong (for example user/password is incorrect). I can't seem to be able to capture this error in order to log it. It just prints this error to the screen.

How do I cause this error not to be printed to the screen, but instead to put it in a variable for use in my script?

Thanks!

user49226
  • 151
  • 2
  • 4
  • 8

7 Answers7

4

Use popen to run the process. The example #2 on this page shows exactly what you're looking for:

<?php
error_reporting(E_ALL);

/* Add redirection so we can get stderr. */
$handle = popen('/path/to/spooge 2>&1', 'r');
echo "'$handle'; " . gettype($handle) . "\n";
$read = fread($handle, 2096);
echo $read;
pclose($handle);
?>
David Schmitt
  • 58,259
  • 26
  • 121
  • 165
  • @edanb:This is a good enough solution. But I am not a fan of bash, so I recommend proc_open if you are willing to spend a little more time on handling errors. – artificialidiot Feb 02 '09 at 19:25
2
exec("mysqldump -u user -p passwod database >  outputfile.sql 2> error.log");
Luis Melgratti
  • 11,881
  • 3
  • 30
  • 32
2

You need to redirect stderr to stdout, so you can capture it. This example routes stdout to devnull (thus ignoreing it) and routes stderr to you:

exec('ls * 2>&1 1>/dev/null');
Michael Haren
  • 105,752
  • 40
  • 168
  • 205
1

I'm not too hot in Unix (New Years Resolution...) but these functions look helpful:

  • shell_exec - returns result as a string.
  • passthru - It looks like you can execute this like: passthru('command', $result); and then use $result.
Ross
  • 46,186
  • 39
  • 120
  • 173
0

Have you looked at the system() command? It's been a while since I did any PHP, but that rings a bell.

genesis
  • 50,477
  • 20
  • 96
  • 125
ZombieSheep
  • 29,603
  • 12
  • 67
  • 114
0

tried using backticks?


$var = `command`;

jishi
  • 24,126
  • 6
  • 49
  • 75
0

The following will route stderr messages to the same place as the normal output.

exec("mysql_dump blah 2>&1",$output,$return_val)
if($return_val !== 0) 
echo "there was an error"

2>&1 means re-route stderr messages to the same place as stdout, and thus will be loaded into the output array.

jcampbell1
  • 4,159
  • 3
  • 33
  • 35