Laravel exec() produce a mysql-dump empty file - php

I'm using exec() for execute mysql-dump but it's generating an empty file on apache, but when i use the "php artisan serve" the file is generated correctly, the output file has the same user and group in apache and in the artisan serve.
Using: Ubuntu 14.04 and Xamp 5.6.12
$dir = substr(__DIR__, 0, 24).'database/backups/';
$newBackup = Backup::create();
$command = 'mysqldump -uroot lions > '.$dir.$newBackup->getDateTimeString().'.sql';
exec($command);

Ok, I was facing the same problem with Laravel 5.6 and running windows though. Before anything, you should make sure to include the password argument (either as --password or -p), even if its empty.
$cmd =
"mysqldump -h " . env('DB_HOST') .
" -u " . env('DB_USERNAME') .
" -p\"" . env('DB_PASSWORD') . "\"" .
" --databases " . env('DB_DATABASE');
The main issue is that even though several sources note that exec waits until the process is complete there is no way to know for sure, leaving that aside, since processes could be owned by different users it'd probably be better if you created a temporary file and then flashed the contents of the output array into it rather than hoping for mysqldump to do it for you.
$output = [];
$name = "your_random_file_name.sql";
exec($cmd, $output);
$tmppath = tempnam(sys_get_temp_dir(), $name);
$handle = fopen($tmppath, "w");
fwrite($handle, implode($output, "\n"));
Finally, write the main file to your desired location, in my case I upload it directly to an Amazon S3 bucket, and close the temporary file.
Storage::disk('myS3bucket')
->putFileAs("backups", new File($tmppath), $name);
fclose($handle);
I know it seems redundant but, as I mentioned above, there is no way to know for sure.

Indeed, in a development environment, it is customary not to set a password for the database. And that's why your command does not work.
But in a production environment, you are obliged to set a password for the database.
Try in your production environment (ie with a password!), And you will see that the script works.

I don't have a solution for this problem but I do know it should be possible to do this. If I enter the following command in my terminal the mysqldump works:
mysqldump "--user=root" "--password=" dbname > ~/Desktop/export.sql
But when I use this command in my scheduler as below, I gett an empty file.
$schedule->exec("mysqldump \"--user=".env('DB_USERNAME')."\" \"--password=".env('DB_PASSWORD')."\" ".env('DB_DATABASE')." > export.sql")->everyMinute();
Maybe there is someone who knows why this doesn't work? I'm guessing it's a permission issue, but I leak experience in this.

Related

PHP shell_exec() not executing -- no errors

I created this DB Copy tool for my company, and everything is completely functional locally. I rsync'ed it to our tool server and now it seems it is unable to execute the shell command I'm passing with shell_exec.
$command = "/usr/bin/mysqldump -v -u$dbUser -p$dbPass ";
$command .= "-h$sourceHost -P$sourcePort $sourceDB 2>../data/dump.log ";
$command .= "| /usr/bin/mysql -u$dbUser -p$dbPass ";
$command .= "-h$targetHost -P$targetPort $targetDB 2>../data/error.log";
$output = shell_exec($command);
I capture the stderr output of the mysql dump, because that is actually used by mysqldump to show progress (dumping this table, dumping this table etc) and I read from that file on my page to show progress.
Neither of the files specified are even being created. This makes me think there is some sort of permissions issue. However I can see that my directories all have the same permissions as others on this server for working tools. Doesn't rule it out, but I'm not sure what to assess further.
I tried changing shell_exec() to exec() and adding a variable to capture the output ( exec($command, $shellOutput) ) and $shellOutput was empty.
I echo'd the command to be run, after it is formed by the script, and was able to run that on the server with no issues.
I'm a bit at a loss here, as it's not even giving me any feedback to work with. Any ideas on what I can try?
To add context, this is a page that is being called by $.ajax to kick off this dump. After this shell command, there is an echo of what db was copied, and that is returning. So the page is being called correctly, it seems to only be the shell command itself that is simply not working.
Thanks in advance.
*Also worth noting that our directory structure is such that our www folder of our project is symlinked to the documentRoot of the server.
You can try system("ur command 2>&1");
This should work and if not output why it doesn't work.
Am sure its to do with your permissions
ls -ld directory
If thats the problem change mode chmod to your preference
Etan had it correct. It was something new to me that the files are created before anything it run (but it makes complete sense). I took the files out, and the command ran. I ended up having to give apache permission to write to the data directory in my project.
Still wrapping my head around linux permissions.
Thanks all.

Using mysqlimport inside PHP script

I'm trying to import lot's of CSV files into a MySQL DB programmatically.
After some research, I found LOAD DATA, but it is not a possibility, as the server don't allow it.
Then, I found mysqlimport a viable alternative.
Here's what is happening:
I download lot's of CSV files from a FTP server and, one by one, I execute the folowing:
exec("ln " . $path . $csv_file. " " . $path . "CSVs.txt");
exec("mysqlimport -u root -ppass --local --ignore-lines=1 --columns=column1,column2 " . $path . "CSVs.txt>" . $path . "_.txt");
unlink($path . "CSVs.txt");
First, I create a symlink of the file (as I didn't manage to use the file name different from the table name)
Then, I execute the mysqlimport command, sending the output do a txt file.
Finally, I remove the symlink.
When I run, the CSV temp file is created and deleted, but nothing apear on my DB, nor in the output txt.
If I echo the command and past in my terminal, it works flawlessly, but, in the exec, nothing happens.
I believe it has something to do with the quotes and backslashes, but couldn't manage to fix it.
Any help will be appreciated :P
EDIT: I already chmod**ed the **mysqlimpot bin… still didn't work!
It seem like PHP wasn't finding mysqlimport command. So, I had to use it's full path to make it work!

How to export full mysql database with php script...? Problem in using 'mysqldump'

i am using this command to backup my full mysql database..
$backupFile = $dbname . date("Y-m-d-H-i-s") . '.sql';
$command = "mysqldump -h$hostname -u$username -p$password $dbname > $backupFile";
system($command);
I am getting blank file.
And i am using XAMMP on windows.
I have already used exec() but also getting blank file.
And but on shell it has successfully done.
Whats wrong in this code.
The best thing you can do is check what is going wrong. You might even want to check outside of PHP to see what you are doing. So echo your $command, and look at it, see if it looks correct. Then use it on the commandline, see if you can get it to work.
Possible attention points:
Do you have any 'strange' characters (like &) in your password? You might need to escape them
Is the mysqldump command available? (is it in your PATH, or in the dir where you are running this from
Are you allowed to do any system/exec commands at all?
Is the user that runs your php code (apache?) allowed to do this command?
Is the user that runs this code allowed to write in this directory?
To test your current command, you might want to do this:
- replace your system command with an echo: echo $command;
- run the script and copy the command you see there.
- Open a terminal. (start->run->"cmd")
- goto the dir where your script is / runs.
- paste /type the command.
- check your result.
I do not know what happens when you do not have a password, but still supply the -p option. It might try and ask for a password anyway, as you've indicated you want to enter a password, but have not provided it. I do not know this for sure, that's why you might want to check it. (#wimvds confirms in the comment: if you supply a -p and no password, you'll get a "password: " dialog.)
In the commandline you can check what command you need to type to get the mysqldump to work. If that's ok, then make sure your script actually issues that command. Then test again with the script.

mysqldump and wamp

Update: Finally got this thing working but still not sure what the problem was. I am using a wamp server that I access through a networked folder.
The problem that still exists is that to execute the mysqldump I have to access the php file from the actual machine that is being used to host the WAMP server.
End of update
I am running a wamp server and trying to use mysqldump to backup a mysql database I have. The following is the PHP code I am using to run mysqldump.
exec("mysqldump backup -u$user -p$pass > $sql_file");
When I run the script the page just loads inifnately and the backup is not created.
A blank file is being created so I know something is happening.
Extra info:
* exec() is not disabled
* PHP is not running in safe mode
Any ideas??
Win XP, WAMP, MYSQL 5.0.51b
mysqldump is likely to exceed the maximal time php is supposed to run on your system. Try using the command in cmd or increase the max_execution_time in your php.ini .
Are you sure $pass is defined and doesn't have a space character at the start?
If it wasn't, mysqldump would be waiting for command line entry of the password.
I had the same thing happen a while back. A co-worker pointed me to the MySQL GUI tools and I have been making backups with that. The Query Browser that comes with it is nice, too.
MySQL GUI tools
It might help to look at the stderr output from mysqldump:
$cmd = "mysqldump backup -u$user -p$pass 2>&1 > $sql_file";
exec($cmd, $output, $return);
if ($return != 0) { //0 is ok
die('Error: ' . implode("\r\n", $output));
}
Also you should use escapeshellarg() if $user or $pass are user-supplied.
I've also struggled with using the mysqldump utility. I few things to check/try based on my experience:
Is your server set up to allow programs to run programs with an exec command? (My webhost's server won't let me.) Test with a different command.
Is the mysqldump utility installed? Check with whereis mysqldump.
Try adding the optimize argument --opt

PHP MySQL Backup script on IIS Server

Bit of a newbie, so please excuse the lack of terminology. . . .
I have a PHP script to backup a MySQL database "dbjobs".
I've tried nearly everything I can but can't get it to work.
It works if I run the $command directly from the Command Prompt on the server, but everytime I try to run the PHP version, I get an HTTP 500 error.
<?php
$backupFile = "DBJobs_" . date("Y-m-d");
$command = "\"mysqldump.exe\" --opt -hlocalhost -uUser -pPasswword dbjobs > c:/backup.sql";
$result = system($command);
if ($command !== false) {
echo "<p>Backup file created!</p>";
}
else {
echo "<p>There was a problem!</p>";
}
?>
I have tried the exec() function instead of system() but still does the same.
Does anyone know where I am going wrong?
Thanks
It's very likely both a path issue (the web server doesn't know where the executable is) and a permission issue. Typically, IIS isn't able execute a shell (cmd.exe) and so isn't going to be able to run the executable, so it would have to have permissions to get a shell and to run the MySQL utility.
Your other alternative is to have the database do it for you with a select statement that writes to an output file.
A couple of options to try are:
full path to the mysqldump.exe in the $command line of code
You might try backticks $command instead of system (backticks key also has the tilda symbol when you shift)
Could be a permissions issue???
You have to grant read/execute permissions to the account under which IIS is running on C:\WINDOWS\System32\cmd.exe. Check this out.

Categories