我最终采用的方法并不疯狂(MySQLDump 类似乎是比 exec() 更强大的方法),但在这里它以防万一它对任何人都有帮助。
尽管我不想进行操作系统检测,但乍一看,我似乎无法解决报价解释中的问题。令人高兴的是,操作系统检测相对容易,如果您准备做出一些假设,例如“如果它不在 Windows 上运行,那么它在某种 *nix 服务器上”。
这是我的基本方法,我相信它会被激怒。
// Inside class
protected $os_quote_char = "'"; // Unix default quote character
// Inside constructor
// Detect OS and set quote character appropriately
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
$this->os_quote_char = '"';
// Method for adding quotes
/**
* Adds the OS non-interpreted quote character to the string(s), provided each string doesn't already start with said quote character.
*
* The quote character is set in the constructor, based on detecting Windows OSes vs. any other (assumed to be *nix).
* You can pass in an array, in which case you will get an array of quoted strings in return.
*
* @param string|array $string_or_array
* @return string|array
*/
protected function os_quote( $string_or_array ){
$quoted_strings = array();
$string_array = (array) $string_or_array;
foreach ( $string_array as $string_to_quote ){
// don't quote already quoted strings
if ( substr( $string_to_quote, 0, 1 ) == $this->os_quote_char )
$quoted_strings[] = $string_to_quote;
else
$quoted_strings[] = $this->os_quote_char . $string_to_quote . $this->os_quote_char;
}
if ( is_array( $string_or_array ) )
return $quoted_strings;
else
return $quoted_strings[0];
}
// Actual usage example:
if ( function_exists( 'exec' ) ){
list( $user, $pwd, $host, $db, $file ) = $this->os_quote( array( DB_USER, DB_PASSWORD, DB_HOST, DB_NAME, $backup_file.'.sql' ) );
$exec = $this->get_executable_path() . 'mysqldump -u' . $user . ' -p' . $pwd . ' -h' . $host . ' --result-file=' . $file . ' ' . $db . ' 2>&1';
exec ( $exec, $output, $return );
}