What are the best practices for handling IP address retrieval in PHP scripts running in a CLI environment?
When running PHP scripts in a CLI environment, retrieving the client's IP address can be a bit tricky since there is no direct access to the $_SERVER superglobal variable. One way to handle this is by using the getenv() function to retrieve the value of the 'SSH_CLIENT' environment variable, which typically contains the client's IP address in CLI mode.
$ipAddress = '';
if (getenv('SSH_CLIENT')) {
$ipAddress = explode(' ', getenv('SSH_CLIENT'))[0];
} else {
$ipAddress = '127.0.0.1'; // Default to localhost if IP address is not available
}
echo "Client's IP address: $ipAddress";