How can the Hosts file be utilized in a Windows environment to map an IP address to a domain for testing purposes in PHP?

To map an IP address to a domain for testing purposes in PHP in a Windows environment, you can utilize the Hosts file. By adding an entry in the Hosts file mapping the domain to the IP address, you can test your PHP code with the specified domain without needing to modify DNS settings.

// Example of mapping an IP address to a domain in the Hosts file for testing purposes
$ip_address = '127.0.0.1';
$domain = 'example.com';

// Add entry to Hosts file
$hosts_file = 'C:\Windows\System32\drivers\etc\hosts';
$entry = "\n" . $ip_address . "\t" . $domain;
file_put_contents($hosts_file, $entry, FILE_APPEND);

// Test PHP code with specified domain
$test_url = 'http://' . $domain;
$response = file_get_contents($test_url);
echo $response;