Core\Uri::userInfo
$uri->userInfo(): ?stringReturns the user part of an address, which is the text between // and @. For ftp://ann@files.example.com/, userInfo() returns ann.
Some addresses also have a password after a :, such as ann:secret. The user and the password are returned as one text, and userInfo does not split them. Writing a password in an address is not safe, because addresses are often saved in logs.
Escapes such as %40 stay in the result. Use Core\Uri::decodeComponent to decode them.
The result is null when the address has no @ before its host. It is "" when nothing is written before the @.
The examples below read the user part, decode an escaped user part, and check that a database address in the settings has no password in it.
Return value
Returns ?string. The user part, without the @. The result is null when the address has no @ before its host. It is "" when nothing is written before the @.
Examples
Read the user
<?nvs// Shows how to read the user part of an address, which is the text between `//` and `@`.
array<string> $addresses = [ 'ftp://ann@files.example.com/report.pdf', 'ssh://deploy@build.example.com/', 'https://example.com/',];
// This prints ann, deploy and "no user".foreach ($addresses as string $address) { ?string $user = Core\Uri::parse($address)->userInfo(); echo $user ?? 'no user', "\n";}anndeployno userDecode an escaped user
<?nvs// Shows how to decode a user part that contains escapes.
Core\Uri $mail = Core\Uri::parse('imap://ann%40example.com@mail.example.com/');
// `userInfo` returns the escapes as they were written. This prints ann%40example.com.string $written = $mail->userInfo() as string;echo $written, "\n";
// `Core\Uri::decodeComponent` turns `%40` back into `@`. The result is `bytes`.// This prints ann@example.com.echo Core\Uri::decodeComponent($written) as string, "\n";ann%40example.comann@example.comFind a password in a setting
<?nvs// Shows how a program checks that a database address in its settings has no password in it.
class Settings{ public static function check(string $address): string { // `?? ""` gives an empty text when the address has no user part. string $user = Core\Uri::parse($address)->userInfo() ?? ''; // A password is written after a `:` in the user part, such as `app:secret`. if (Core\Str::contains($user, ':')) { return 'error: move the password out of the address'; } return 'ok'; }}
// This prints "ok" twice, then the error once.echo Settings::check('postgres://app@db.example.com/shop'), "\n";echo Settings::check('postgres://db.example.com/shop'), "\n";echo Settings::check('postgres://app:secret@db.example.com/shop'), "\n";okokerror: move the password out of the address