【问题标题】:catch postgresql command execution error from php file从 php 文件中捕获 postgresql 命令执行错误
【发布时间】:2012-05-24 12:29:37
【问题描述】:

我是 php 的初学者,遇到了一些问题:

我有一个 php 文件,其中有一个函数 create_dump(),我在其中使用 pg_dump 转储我的 postgresql 数据库强>命令。
现在,当从 linux 终端执行 php 文件时,它会在终端上要求 postgresql 密码
如果用户无意中为数据库提供了错误的密码,我想在我的 php 文件中添加错误处理。

换句话说:
如何从我的 php 文件中捕获 pg_dump(postgresql 命令)执行错误?
谢谢!

【问题讨论】:

  • 您能否提供在您的 PHP 脚本中运行该命令的代码?
  • php 文件中 create_dump 函数中的命令代码为:$command="/usr/bin/pg_dump --a --no-owner --no-acl --attribute-inserts --disable-dollar-quoting --no-tablespaces --host=".$db['hostname']." --user=".$db['username']." --password --port=" .$db['port']." ".$db['database']." >".$path['schema_path']."schema-'$latest_update'.sql"; $output = passthru($command);

标签: php postgresql-9.1


【解决方案1】:

根据您提供的信息,我有一个您想要做的解决方法。首先,您需要使用 --file=some_file.sql 标志,而不是使用“>”管道输出转储的输出,它执行相同的工作。

现在,即使您将 stderr 发送到 stdout,来自 passthru 调用的 $output 似乎也不会捕获输出,所以这就是可行的方法。您将使用 --file= 标志修改命令并将命令的输出(包含错误)通过管道传输到日志文件,同时确保还将 stderr 发送到 stdout(在命令之后执行 2>&1),以便捕获错误。

代码如下:

// notice the file= flag and the piping of error to the file
$command=
    "/usr/bin/pg_dump --a --no-owner --no-acl --attribute-inserts ".
    "--disable-dollar-quoting --no-tablespaces ".
    "--file={$path['schema_path']}schema-{$latest_update}.sql ".
    "--host={$db['hostname']} --user={$db['username']} ".
    "--password --port={$db['port']} {$db['database']} > pg_dump_error.log 2>&1"; 

// no output to capture so no need to store it
passthru($command);

// read the file, if empty all's well
$error = file_get_contents('pg_dump_error.log');
if(trim($error) != '')
    exit("PG_DUMP ERRROR:\n-----\n$error\n");

希望这或多或少是您想要的。

【讨论】:

    猜你喜欢
    • 2016-12-02
    • 2012-09-03
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多