我希望得到一個URL的響應,說http://www.google.com使用下面的代碼:執行HTTP請求
$fp = @fopen("http://www.google.com/", "r");
,但它始終返回false。 我也試過這個:
@file_get_contents("http://www.google.com/");
沒有希望。 有人可以幫我嗎?
我希望得到一個URL的響應,說http://www.google.com使用下面的代碼:執行HTTP請求
$fp = @fopen("http://www.google.com/", "r");
,但它始終返回false。 我也試過這個:
@file_get_contents("http://www.google.com/");
沒有希望。 有人可以幫我嗎?
對於HTTP請求,您可以使用file_get_contents()
,但您必須確保正確設置正確的流上下文。
看看這段代碼(從PHP手冊here拍攝):
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.google.com/', false, $context);
這應該工作,即使執行PHP中的HTTP請求,更好的辦法是確保在使用cURL擴展,和許多人一樣建議在這個線程中。
僅當配置標誌allow_url_fopen
被設置時才能使用標準文件功能打開URL。這是一個系統級的設置,所以你可能需要編輯你的php.ini來啓用它。
您可以使用捲曲檢索HTML這樣
function get_html($url){
/**
* Initialize the cURL session
*/
$ch = curl_init();
/**
* Set the URL of the page or file to download.
*/
curl_setopt($ch, CURLOPT_URL,$url);
/**
* Ask cURL to return the contents in a variable
* instead of simply echoing them to the browser.
*/
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
/**
* Execute the cURL session
*/
$contents = curl_exec ($ch);
/**
* Close cURL session
*/
curl_close ($ch);
return $contents;
}
這是更好的使用捲曲http://www.php.net/manual/en/curl.examples-basic.php
也可能是從發出HTTP連接阻止PHP軟件防火牆。
我寫了一個獨立於PHP模塊的小HTTP客戶端庫。它捆綁在videodb.net php軟件包中,包括緩存機制,HTTP 1.0/1.1,代理支持等。如果感興趣,請檢查core/httpclient.php。
你的`allow_url_fopen` ini設置是什麼? – 2011-12-16 16:20:00
我會禁用錯誤抑制(在這些函數前刪除`@`)並確保在你的php.ini文件中啓用了`allow_url_fopen`。讓我們知道生成的錯誤是什麼一旦你完成了。 – 2011-12-16 16:20:03