2014-10-29 120 views
1

为什么PHP的file_get_contents不适用于某些URL?PHP file_get_contents不适用于某些URL

<?php 
    $html = file_get_contents('http://modagram.com'); 
?> 

对于上面我收到这样的警告:

PHP Warning: file_get_contents(http://modagram.com): failed to open stream: HTTP request failed! in /var/www/html/scraping/test.php on line 2 
+1

可以确认您在php.ini中将'allow_url_fopen'设置为ON? – ChelseaStats 2014-10-29 13:14:56

+0

allow_url_open设置为是,它也适用于其他网址,但不适用于http://modagram.com – torayeff 2014-10-29 13:18:35

+0

@Glavić我看着那个线程,但有解决方案没有解释 – torayeff 2014-10-29 13:20:46

回答

1

像@MarkBaker中的评论称,W​​eb服务器可能是拦截未知UserAgents,试图伪造一个:

$context = stream_context_create([ 
    'http' => [ 
     'user_agent' => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)', 
    ], 
]); 
$html = file_get_contents('http://modagram.com', false, $context); 

print_r($http_response_header); // see response headers 
相关问题