简体   繁体   中英

Is there a programmatic way to distinguish whether bash script was executed by user and via shell_exec in PHP?

I've written simple DB backup script that does the job with no issues whatsoever, but to avoid embedding any credentials, I pass everything as arguments.

private function dumpDatabase(): void
{
    $this->fileSystem->disk('local')->makeDirectory('temp');

    $relativePathToDump = 'storage/app/temp/dump.sql';

    $executableChunks = [
        'HOST=' . config('database.connections.mysql.host'),
        'PORT=' . config('database.connections.mysql.port'),
        'USER=' . config('database.connections.mysql.username'),
        'PASSWORD=' . config('database.connections.mysql.password'),
        'DATABASE_NAME=' . config('database.connections.mysql.database'),
        'RELATIVE_PATH_TO_DUMP=' . $relativePathToDump,
        base_path('bin/backup_database.sh'),
    ];

    $command = implode(' ', $executableChunks);

    shell_exec($command);
}

The script itself:

#!/usr/bin/env bash

mysqldump --force --routines -h $HOST --port=$PORT -u $USER -p$PASSWORD $DATABASE_NAME > $RELATIVE_PATH_TO_DUMP

Is there a way to immediately stop the script's execution if it was triggered by user manually via:

./bin/backup_database.sh

but let it do the job when called via:

shell_exec($command);

I could add more checks to see if arguments are present:

if [[ -z "${HOST}" ]]; then
  echo "Database host (HOST=) has not been provided."
  exit 1
fi

but this is not about arguments but about who / what is the "executee" of the script. Is it doable?

if [[ not triggered programatically by shell_exec ]]; then
  echo "Bye"
  exit 1
fi

You can look at the name of the parent process (see Get the name of the caller script in bash script ). Look for php in the PARENT_COMMAND .

caller=$(ps -o comm= $PPID)
if [[ "${caller}" =~ php ]]; then
   echo "Bingo"
fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM