Search code examples
phplaravelcommandexec

mysqldump my database on server returns 2


This issue keeps coming back after many solutions I tried. I am trying to mysqldump my database and compress it using gzip using a single command in PHP/Laravel, this is the latest command I tried:

$filename = "backup-" . Carbon::now()->format('Y-m-d') . ".gz";
$command = "mysqldump -u " . env('DB_USERNAME') . " -p'" . env('DB_PASSWORD') . "' " . env('DB_DATABASE') . "  --no-tablespaces -C | gzip > " . public_path("DBbackup\/") . $filename;
$returnVar = NULL;
$output  = NULL;

exec($command, $output, $returnVar);

it return 2 not 0 meaning that the command failed, and the output is nothing.

then I tried to return the command to check if every variable like env(..) is correct and so on but everything was good, so I tried the command myself and it worked and created the .gz file. I don't understand why using PHP it didn't work?


Solution

  • I don't have enough reputation to comment on the original question so I have to leave my comments as an answer. There is one thing that is highly likely to be causing the problem you're experiencing.

    You can't load environment variables outside of your configuration files in Laravel in some circumstances. I know this is true when your configuration is Cache'd but it may also apply to the environment type you've set in the .env file (IE Production / Local etc).

    It's also bad practice to do so as mentioned in this article: You should never use env() outside of your config files

    What you can do is create your own configuration file that references these environment variables or use configuration files already in place such as the Database.php configuration file that ships with Laravel.

    It's not explicitily mentioned in the Configuration Documentation but it does say this:

    All of the variables listed in the .env file will be loaded into the $_ENV PHP super-global when your application receives a request. However, you may use the env function to retrieve values from these variables in your configuration files.

    I think the wording hints that you should not reference the env function outside of configuration files. I say this as it says you can use the env function in configuration files, as opposed to anywhere in the application. It may be said explicitly somewhere else in the documentation that you can't do this but I'm trying to find that now.

    EDIT: I found an article that explains this available here: env() Gotcha

    EDIT 2: Here is where it's mentioned in the official Laravel Docs: Configuration Caching