Skip to content

Instantly share code, notes, and snippets.

@sebastianbergmann
Last active February 26, 2025 11:09
Show Gist options
  • Save sebastianbergmann/0e52fc954943290e72240f0533ea5406 to your computer and use it in GitHub Desktop.
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
<?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;
}
<?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