Last active
March 4, 2021 08:23
-
-
Save Mandorlo/93837eef8c5f8707b5f91626d75d1a07 to your computer and use it in GitHub Desktop.
PHP command line library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Prompts for a password on the commandline | |
* characters are not visible while the user types | |
* | |
* @param string $prompt (optional default to "Enter Password:") the text inviting the user to enter the password | |
* | |
* @return string the password entered | |
* | |
*/ | |
function read_password($prompt = "Enter Password:") { | |
if (preg_match('/^win/i', PHP_OS)) { | |
$vbscript = sys_get_temp_dir() . 'prompt_password.vbs'; | |
file_put_contents( | |
$vbscript, 'wscript.echo(InputBox("' | |
. addslashes($prompt) | |
. '", "", "password here"))'); | |
$command = "cscript //nologo " . escapeshellarg($vbscript); | |
$password = rtrim(shell_exec($command)); | |
unlink($vbscript); | |
return $password; | |
} else { | |
$command = "/usr/bin/env bash -c 'echo OK'"; | |
if (rtrim(shell_exec($command)) !== 'OK') { | |
trigger_error("Can't invoke bash"); | |
return; | |
} | |
$command = "/usr/bin/env bash -c 'read -s -p \"" | |
. addslashes($prompt) | |
. "\" mypassword && echo \$mypassword'"; | |
$password = rtrim(shell_exec($command)); | |
echo "\n"; | |
return $password; | |
} | |
} | |
/** | |
* Enable colors in shell echo | |
*/ | |
function sqd_echo() { | |
// see https://stackoverflow.com/questions/34034730/how-to-enable-color-for-php-cli/34034922 | |
$patterns = ['/\@(default|white)\s?/', '/\@red\s?/', '/\@green\s?/', '/\@yellow\s?/', '/\@blue\s?/', '/\@magenta\s?/', '/\@cyan\s?/']; | |
$replacements = ["\033[39m", "\033[31m", "\033[32m", "\033[33m", "\033[34m", "\033[35m", "\033[36m"]; | |
echo "\033[39m"; | |
foreach (func_get_args() as $arg) { | |
if (gettype($arg) != 'string') $arg = json_encode($arg, JSON_PRETTY_PRINT); | |
$arg = preg_replace($patterns, $replacements, $arg); | |
echo $arg." "; | |
} | |
echo "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment