Salehin Rafi Salehin Rafi -4 years ago 99
PHP Question

Using PHP script: why mysqldump does not dump sql file?

Hye, I'm new in PHP and trying to use mysqldump using php script.

I already try using command and the dump process is success.
The situation is, when I tried dump using my local computer, the dump is succeed.
But when the code is transfer into the server, mysqldump doesn't work. I have tried almost the solution related to mysqldump topics, but still it doesn't work. I hope someone can guide me. TQ

<?php

/*-----------------------------------------------
MYSQLDUMP FOR SERVER
------------------------------------------*/


$dbhost = "*****";
$dbuser = "*****";
$dbpass = "*****";
$dbname = "*****";

//set date today
$today=date("d-m-Y");

//set file name
$filename = "leave_".$today.".sql";

//MYSQLDUMP

//For Server
$command = sprintf("/usr/bin/mysqldump --opt -h%s -u%s -p%s %s >/var/www/html/leave/leave/backup/%s",

//for local
//$command = sprintf("c:\AppServ\MySQL\bin\mysqldump --opt -h%s -u%s -p%s %s > %s",

$dbhost,
$dbuser,
$dbpass,
$dbname,
$filename
);
system($command);



/*-------------------------------------------------------------
TO SAVE FILE SQL INTO LOCAL
---------------------------------------------------------------*/

$file = "leave_".$today.".sql";
if(!$file)
{
// File doesn't exist, output error
die('File not found');
}
else
{
// Set headers to ask user where to save file.
header('Pragma: anytextexeptno-cache', true);
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: text/plain");
header("Content-Disposition: attachment; filename=$file");

// Read the file from disk
readfile($file);


}



?>

Answer Source

Okay, actually I already solve this issues a few days later after I post the question. Unfortunately, I didn't have enough reputation to post an answer.So here we go.

Here are a few things that need to TAKE NOTE:-

  1. Compulsory to use absolute path for MySQL dump.
  2. Try using --opt (default option for MySQL dump). Read more here.
  3. For the option, if use short form, no need to have (--). eg: --p. Use (--) when use full form. eg: --password. So use '-p' instead of '--p' (applied for others option too).
  4. try 'shell_exec' or 'system' if mysqldump doesnt work on 'exec'.
  5. try avoid have space between option and variable. Eg: -p$dbpass

*Also bear with mind, it involves with permission whether system command can be executed from php or not.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download