Posterous theme by Cory Watilo

Dump mysql db from php (hack) and capture STDERR

Сразу скажу: решение не пройдет на всех хостингах, потому как вызывать сторонние процессы или shell-команды может быть запрещено настройками сервера! Быстрое и простое решение было таким: [cc lang="php"] $out = exec_cmd("mysqldump -Q -u '$[db_user' --password='$db_pass' $db_name " .(isset($db_tables)?$db_tables:'') ." | bzip2 --best -f > $db_name.sql.bz2"); [/cc] Что есть exec_cmd: [cc lang="php"] function exec_cmd ($cmd) { $out = ''; $error = ''; $descriptorspec = array( 0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w') ); $resource = proc_open($cmd, $descriptorspec, $pipes); if (is_resource($resource)) { $stdin = $pipes[0]; $stdout = $pipes[1]; $stderr = $pipes[2]; while (! feof($stdout)) { $out .= fgets($stdout); } while (! feof($stderr)) { $error .= fgets($stderr); } fclose($stdin); fclose($stdout); fclose($stderr); $exit_code = proc_close($resource); } return array('out'=>$out, 'error'=>$error, 'code'=>$exit_code); } [/cc] Нужно это для того чтобы полностью перехватить STDOUT, STDERR ну и STDIN. Эта фнукция описана в коментах на php.net, только там у пайпа STDERR стоит режим на чтение а не на запись, из-за чего пример не работал. Ну и соответственно получить результат выполнения можно как [cc lang="php"] if($out['out']) $log->Log("Backup DB (binary, STDOUT): $out[out]",'info'); if($out['error']) $log->Log("Backup DB (binary, STDERR): $out[error]",'error'); $log->Log("Binary DB backup is over.",'info'); [/cc] где объект $log служит для протоколирования разных сообщений.
| Viewed
times
Filed under: