正版命令

rseugnpd  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(258)

problem:-
我正在尝试在windows中使用php和mysqldump备份mysql数据库。当我使用wamp服务器时,下面的脚本提供了一个所需的转储。

<?php
   $dbhost = 'localhost';
   $dbuser = 'root';
   $dbpass = '';
   $dbname = 'avita';
   $path = "c:/program files/mysql/mysql server 5.5/bin/";
   $backup_file = "d:/avita/".$dbname . date("Y-m-d-H-i-s") . '.sql';
   $command = $path."mysqldump -u$dbuser ". "avita 2>&1 $backup_file";

   exec($command, $output);
   print_r($output);
?>

同样可以使用windows命令行而不使用任何problem:-

问题是,当我在同一台机器上使用php-mysql-apache手动安装运行同一个脚本时,输出类似于below:-
output:-
数组([0]=>“c:/program”未被识别为内部或外部命令,1=>可操作程序或批处理文件。)
我该怎么解决这个问题?

gz5pxeao

gz5pxeao1#

有两个重叠的误解。 %PATH% (或 $PATH 在*nix环境中)。手动命令行工作的唯一原因是您已经更改到mysql目录,并且windows检查当前目录。试着跑步 mysqldump (与上面一样,没有任何目录限定符)当您的提示符仅显示以下内容时:

C:\>

发生什么事了?没用,但为什么?
接下来,回想一下php的 exec() 是一层薄薄的外壳。让我们假设您正在运行上面的脚本提供的shell。如果没有已知的目录,假设我们在根目录中:

C:\>c:/program files/mysql/mysql server 5.5/bin/mysqldump.exe
`c:/program` is not recognized as an internal or external command,
operable program or batch file

完全一样的问题。。。发生什么事了?引用。shell将空格解释为标记分隔符,因此shell抱怨 c:/program 不是有效的可执行文件。用引号试一下,现在shell明白了整个带空格的“奇怪”路径都是第一个参数,实际上是我们想要的可执行文件的路径:

C:\>"c:/program files/mysql/mysql server 5.5/bin/mysqldump.exe"

突然,一切如期而至!
php有一系列的“剪纸”,其中之一就是对这样的可执行文件的“理智”处理。php就像这里的c一样,您必须自己进行转义。考虑:

$command_parts = [
  escapeshellarg("${path}mysqldump.exe"),
  escapeshellarg("-u$dbuser"),
  "avita",    # no escapeshellarg here, as avita is visually "clean"
  "2>&1",     # no escapeshellarg here, as 2>&1 is visually "clean"
  escapeshellarg($backup_file)
];
$command = implode(' ', $command_parts);
exec( $command );

从这里开始,你的脚本应该按预期工作。

相关问题