Filesize 0 mysqldump - php

I am using Windows 7 and using php i am backing up my database with the help of mysqldump. The file gets successfully written but the size remains always 0. Any idea why is this happening?
Note :- If i type the same command in command line, it works. This is my function :-
public static function BackupDatabase($backupPath){
$fileName = uniqid() .'.sql';
$backupCommand = 'mysqldump -u ' . DBUsername .' -p' . DBPassword .' abc >' . $backupPath . $fileName ;
$retVal = '';
$feedback = system($backupCommand, $retVal);
if($feedback == NULL || $feedback == '')
return 'Database backed up successfully by name ' . $fileName;
else
return $feedback;
}
EDIT :-
public static function BackupDatabase($backupPath){
$fileName = uniqid() .'.sql';
$backupCommand = 'mysqldump -u ' . DBUsername . ' abc > ' . $backupPath . $fileName .' 2>&1' ;
echo $backupCommand;
$retVal = '';
$feedback = system($backupCommand, $retVal);
echo $retVal;
if($feedback == NULL || $feedback == '')
return 'Database backed up successfully by name ' . $fileName;
else
return $feedback;
}
Thanks in advance :)

I believe is caused by the environment setting.
You can execute mysqldump successfully in the command line as you probably has mysqldump register in your environment.
While running in a PHP, the path to mysqldump might not recognized by user that running the web server.
And
$feedback = system('unknown program > file', $retval);
Will always set $feeback = ''; even PHP cannot find where is your mysqldump program, it still pipe a single character to backup file.
You can put in absolute path to mysqldump to test again.

Check your $backupCommand string. It seems to me that there are some spaces missing (e.g. in the vicinity of '-p').

After much headache, this syntax worked for me:
cmd /c " C:\mysqldump.exe -h $mysql_server -u $mysql_user --password=$mysql_password $dbname > C:\Dump.sql "

Related

How to execute commands through PHP?

I am trying to convert videos into MP4 using FFMPEG. I have it set up this way:
.
.
private $ffmpegPath;
public function __construct($con) {
$this->con = $con;
$this->ffmpegPath = realpath("ffmpeg/bin/ffmpeg.exe");
}
.
.
public function convertVideoToMp4($tempFilePath, $finalFilePath){
$cmd = "$this->ffmpegPath -i $tempFilePath $finalFilePath 2>&1";
$outputLog = array();
exec($cmd, $outputLog, $returnCode);
if($returnCode != 0){
foreach ($outputLog as $line){
echo $line."<br>";
return false;
}
}
return true;
}
And in the browser i get the following error:
'C:\xampp\htdocs\Thinksmart First Sprint' is not recognized as an internal or external command".
In my constructor i have it set up to give me the realpath and i suspect that this is what it does in the command line:
C:/xampp/htdocs/Thinksmart FIrst Sprint/ffmpeg/bin/ffmpeg.exe -i (file temp name) (file name i want)
And this should work, but i dont know why it wont. Any ideas? Its my first time working with video conversions.
As you can see, spaces in your command are used to separate arguments. So if there are spaces in a path you need to quote the entire path with quotes so that the shell/processor knows they aren't separators but are one argument:
$cmd = $cmd = '"' . $this->ffmpegPath . '" -i $tempFilePath $finalFilePath 2>&1';
Which will result in a command something like this:
"C:/xampp/htdocs/Thinksmart First Sprint/ffmpeg/bin/ffmpeg.exe" -i C:/path/to/file1 C:/path/to/file2 2>&1
I think only double-quotes work on Windows. You need to quote $tempFilePath and $finalFilePath if they might have spaces in them as well.

Laravel mysqldump create empty file, but same command work when execute via xampp shell

running Laravel 5.2 on Xampp 321 Win7 Mysql5.6 PHP 5.6.3 I cant create BD dump file .sql
$filename = "backup-".Carbon\Carbon::now()->format('Y-m-d_H-i-s').".sql 2>&1";
try{
$command = "mysqldump --user=" . env('DB_USERNAME') ." --password=" . env('DB_PASSWORD') . " --host=" . env('DB_HOST') . " " . env('DB_DATABASE') . " > " . storage_path() . "/" . $filename;
$returnVar = NULL;
$output = NULL;
//exec command allows you to run terminal commands from php
exec($command, $output, $returnVar);
//dd($command);
return 1;
}catch(Exception $e){
return $e->errorInfo; //some error
}
When loading script it generates an empty file! But by doing dd ($ command) and copying paste this text, this command works fine in the Xampp shell. Any ideas please?
Solved with this code: setting absolute path of mysqldump adn adding double backslash to url var
$filename = "backup-".date("d-m-Y-H-i-s").".sql";
$mysqlPath = "D:\\xampp/mysql/bin/mysqldump";
try{
$command = "$mysqlPath --user=" . env('DB_USERNAME') ." --password=" . env('DB_PASSWORD') . " --host=" . env('DB_HOST') . " " . env('DB_DATABASE') . " > " . storage_path() . "/" . $filename." 2>&1";
$returnVar = NULL;
$output = NULL;
exec($command, $output, $returnVar);
return 1;//ok
}catch(Exception $e){
return "0 ".$e->errorInfo; //some error
}

PHP: mysqldump: Couldn't find table: ">"

I tried to make simple php script to backup databes using mysqldump but i got this error:
mysqldump: Couldn't find table: ">"
And this is the function that i have write to make the job:
protected function dump($params, $dbs, $backup_folder)
{
if (!is_writable($backup_folder)) {
throw new Exception(sprintf('The backup folder is not writable: %s',
$backup_folder));
}
$backup_folder = trim($backup_folder, "/"); // be sure that there is no / at the end
$baseCmd = 'mysqldump --hex-blob --routines --skip-lock-tables -h%s -u%s -p%s %s > %s';
foreach ($dbs as $db) {
$dest = sprintf('%s/%s', $backup_folder,
$db . '_' . date('YmdHis') . '.sql');
$cmd = sprintf($baseCmd, $params['host'], $params['user'],
$params['password'], $db, $dest);
echo "Exec: $cmd: ";
$last = system(escapeshellcmd($cmd), $res);
echo $res;
if ( 0 !== $res) {
echo "Fail";
} else {
echo "Done \n";
}
}
}
The command printed by this function give:
mysqldump --hex-blob --routines --skip-lock-tables -hdb-backup -uroot -pMyPwd my_db_name > backups/my_db_name_20151010232734.sql
When i execute this command from Shell it works very well but not from Php script.
My config is:
My Desktop System Shell: Ubuntu 15.04
Mysql Server: Mysql 5.6 installed in Ubuntu Server 15.04
PHP version: 5.6.4
Any help ?
Thank you
The escapeshellcmd() command prepends a \ to the >.
From the PHP documentation:
Following characters are preceded by a backslash: #&;`|*?~<>^()[]{}$\, \x0A and \xFF.
You should either escape each argument individually with escapeshellarg(), or ensure that your method arguments ($params, $db, and $backup_folder) are valid and don't contain one of those chars and just use
system($cmd, $res)
I hope this helps!

PHP LFTP data mirror output

I'm using a Linux local computer and need to backup/mirror some very large file structures regularly. I only have access to SFTP.
I was after a simple one click solution. I originally tried to write the little script in BASH but I've never used it before and am not up to scratch with the syntax so I resorted to PHP. (I do understand PHP is not designed for this kind of work, but I'm on a tight time scale and don't have the time to get into BASH atm)
<?php
//init
parse_str(implode('&', array_slice($argv, 1)), $_GET);
$error = array();
$lPrefix = '/home/hozza/Sites/';
$archiveLocation = '/home/hozza/Backups/';
$lDir = isset($_GET['l']) ? $_GET['l'] : $error[] = 'Local Directory Required';
$rDir = isset($_GET['r']) ? $_GET['r'] : $error[] = 'Remote Directory Required';
$bookmark = isset($_GET['b']) ? $_GET['b'] : $error[] = 'lftp Bookmark Required';
//Check for args
if(count($error) == 0) {
$archiveName = end(explode('/', $lDir)) . '_' . date('Y-m-d_H-i');
//Validate local dir
if(is_dir($lPrefix . $lDir)) {
//preserve Sublime Text 2 config SFTP files
$ST2_SFTP_conf = false;
if(file_exists($lPrefix . $lDir . '/sftp-config.json')) {
$ST2_SFTP_conf = file_get_contents($lPrefix . $lDir . '/sftp-config.json');
unlink($lPrefix . $lDir . '/sftp-config.json');
}
//Start mirror
$lftOutput = explode("\n", shell_exec('lftp -e "mirror -e -p --parallel=10 --log=' . $archiveLocation . 'logs/' . $archiveName . '.txt ' . $rDir . '/ ' . $lPrefix . $lDir . '/; exit top" ' . $bookmark));
//Tar regardless of lftp error or success
$tarOutput = shell_exec('cd ' . $lPrefix . ' && tar -czf ' . $archiveLocation . $archiveName . '.tar.gz ' . $lDir);
//Output completion or errors
shell_exec('notify-send -i gnome-network-properties -t 0 "Mirror & Archive Complete" "' . $archiveName . '\n\n' . implode('\n', $lftOutput) . $tarOutput . '"');
//put back ST2 SFTP conf
if($ST2_SFTP_conf != false) file_put_contents($lPrefix . $lDir . '/sftp-config.json', $ST2_SFTP_conf);
exit;
}
else shell_exec('notify-send -i error -t 0 "Mirror & Archive Error" "' . date('Y-m-d') . ' ' . date('H-i') . '\n' . $lDir . ' \n Does not exist! D:"');
}
else shell_exec('notify-send -i error -t 0 "Mirror & Archive Error" "' . date('Y-m-d') . ' ' . date('H-i') . '\n' . implode('\n', $error) . '"');
?>
It can be run for many sites via a short-cut like so...
terminator -T "Mirror & Archive" -e "php ~/Programs/mirror.php l=local-dir_path r=./ b=lftp-bookmark-name"
If no password is in the LFTP bookmark (there shouldn’t be as it's stored in plain text) the terminal prompts for a password, after the script has run, a nice notification is given with some info about files/folders/speed etc.
However, when the script is running in a terminal, only the "input password" bit is output to the terminal, I would like all the output displayed in the terminal (normally that would display what file/folder is currently working with etc.)
Anyone know how to do that?
IIRC the reason that you see the password prompt output to the terminal is that it is using stderr. You could try redirecting stdout to stderr for your commands which should show you the 'real-time' progress. Tack this on to the end of the shell_exec() command: 1>&2
ie:
shell_exec('lftp -e "mirror -e -p --parallel=10 --log=' . $archiveLocation . 'logs/' . $archiveName . '.txt ' . $rDir . '/ ' . $lPrefix . $lDir . '/; exit top" ' . $bookmark . ' 1>&2')
However, this will preclude you from having anything returned by shell_exec for logging purposes. What I would suggest is something like:
$log_stem = '/tmp/' . time() . '_'; // ie: /tmp/1357581737_
$lfOutfile = $log_stem . 'lftp.log';
$tarOutfile = $log_stem . 'tar.log';
shell_exec('lftp -blah | tee ' . $lfOutfile ' 1>&2' );
shell_exec('tar -blah | tee ' . $tarOutfile ' 1>&2' );
$lfOut = file_get_contents($lfOutfile);
$tarOut = file_get_contetns(tarOutfile);
// remove tmp files
unlink($lfOutfile);
unlink($tarOutfile);
Which will capture a copy of the output to a file before redirecting the output to stderr so you can watch it live.
However, if you want to run this via cron I would recommend against writing anything to stderr that is not an error, otherwise cron will send a warning email every time it is run.
I think the last answer was close:
Either this:
shell_exec('lftp -blah |& tee ' . $lfOutfile );
shell_exec('tar -blah |& tee ' . $tarOutfile );
Or if that still doesn't work try this:
shell_exec('lftp -blah 2>&1 | tee ' . $lfOutfile );
shell_exec('tar -blah 2>&1 | tee ' . $tarOutfile );

MySQL database restore using PHP

I'm trying to restore MySQL dump created the following way:
$file = '/path/to/file.sql';
exec('mysqldump -u '.DB_USER.' -p'.DB_PASS.' '.DB_NAME.' > '.$file);
the above creates the dump as expected, then to restore I'm trying to use the following:
$file = '/path/to/file.sql';
exec('mysql -u '.DB_USER.' -p'.DB_PASS.' '.DB_NAME.' < '.$file);
but for some reason it doesn't do anything.
Please note that the constants contain the relevant database connection parameters.
Any idea what I'm doing wrong?
use mysql -e 'source $file' instead of redirection
$file = realpath('file.sql');
exec('mysqldump -u ' . DB_USER . ' -p' . DB_PASS . ' ' . DB_NAME . ' > ' . $file);
Perhaps try this.

Categories