ラボ > PHP:通信絡み、各種エラー、ファイル関連、サーバ:Xampp

PHP file_get_contents()+Win:Xampp+localhostでタイムアウト

localhostのデータが取得できない

作成日:2020-05-28, 更新日:2020-05-28

対策

・「/etc/hosts」にローカルIPでlocalhostを指定

▼「/etc/hosts」に追加

192.168.xxx.xxx hoge.localhost

経緯

・Win+Xamppの環境(サブドメイン設定:Xamppでサブドメインを使う(hosts、httpd-vhosts.conf)
・localhostを「file_get_contents()」で取得しようとすると「false」が返ってくる
→調べるとタイムアウトしていた。

▼「cURL()」に変更してもエラー。そのときのエラー

Connection timed out after 20000 milliseconds

当初の設定

サーバ側(Win側?):apache

・1つのXamppで複数のドメインを使いたいのでサブドメインを指定
→「xampp\apache\conf\extra\httpd-vhosts.conf」で設定

サーバ側(Win側?):hosts

▼「/etc/hosts」

127.0.0.1 localhost
127.0.0.1 hoge.localhost

PHP

$url = 'http://hoge.localhost/hogehoge.html';
var_dump(file_get_contents($url));

→結果は「false」。

修正後の設定

「/etc/hosts」の設定は「127.0.0.1」だけじゃなく「192.168.xxx.xxx」も紐づけが必要っぽい

サーバ側(Win側?):hosts

▼「/etc/hosts」

127.0.0.1 localhost
127.0.0.1 hoge.localhost
192.168.xxx.xxx hoge.localhost

※「192.168.xxx.xxx」はwinのcmdからipconfigで調べる。

複数あるとき

127.0.0.1 localhost
127.0.0.1 hoge.localhost foo.localhost
192.168.xxx.xxx hoge.localhost foo.localhost

関連項目

Xamppでサブドメインを使う(hosts、httpd-vhosts.conf)