Last active
February 26, 2025 11:09
-
-
Save sebastianbergmann/0e52fc954943290e72240f0533ea5406 to your computer and use it in GitHub Desktop.
PHP: Getting the name of the host a script is running on and the name of the operating system user that the PHP process runs under
This file contains hidden or 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 declare(strict_types=1); | |
/** | |
* @return non-empty-string | |
*/ | |
private function hostname(): string | |
{ | |
$candidate = gethostname(); | |
if ($candidate === false) { | |
return 'unknown'; | |
} | |
$candidate = trim($candidate); | |
if ($candidate === '') { | |
return 'unknown'; | |
} | |
return $candidate; | |
} |
This file contains hidden or 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 declare(strict_types=1); | |
/** | |
* @return non-empty-string | |
*/ | |
function userName(): string | |
{ | |
if (function_exists('posix_getpwuid') && function_exists('posix_geteuid')) { | |
$candidate = trim(posix_getpwuid(posix_geteuid())['name']); | |
} elseif (PHP_OS_FAMILY === 'Windows') { | |
$candidate = trim((string) getenv('USERNAME')); | |
} | |
if (!isset($candidate) || $candidate === '') { | |
return 'unknown'; | |
} | |
return $candidate; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment