當我發送帖子請求時,有一些問題。 我用這個腳本執行頁面http://localname.local/test
,頁面http://localname.local/directory/page.php
得到一個json數據。curl或file_get_contents不起作用
$url = "http://localname.local/directory/page.php";
$post = [
"key1" => "hello",
"key2" => 885,
];
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($post),
'timeout' => 10
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === false) {
// Handle error
return null;
}
else
return $result;
但經過10個secondes,劇本得到的消息:
Warning: file_get_contents(http://localname.local/directory/page.php): failed to open stream: HTTP request failed! in D:\ ... \html\test.php on line X
的page.php文件作品,我可以送崗位要求與我的瀏覽器作爲客戶端,但PHP(或WAMP)可以」訪問或發送請求到自己的頁面。
我得到了PHP 7.1.7,Apache 2.4.23在wam 3.0.9上,選項allow_url_fopen
打開。
編輯: 爲捲曲
public static function get_content($post)
{
$url = "http://localname.local/directory/page.php";
$query = http_build_query($post);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10); // Tell cURL that it should only spend X seconds trying to connect to the URL in question.
curl_setopt($curl, CURLOPT_TIMEOUT, 10); // A given cURL operation should only take X seconds max.
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // returns data to function
curl_setopt($curl, CURLOPT_POSTFIELDS, $query);
$data = curl_exec($curl);
if (curl_errno($curl))
throw new Exception(curl_error($curl));
curl_close($curl);
return $data;
}
得到
Fatal error: Uncaught Exception: Operation timed out after 10000 milliseconds with 0 bytes received in D:\ ... \html\test.php on line X
Exception: Operation timed out after 10000 milliseconds with 0 bytes received
「test.php」通常(甚至有時)是否需要超過5秒才能運行? – ceejayoz
不,它運行速度很快。 WAMP配置爲30秒,但在控制服務器之前我必須等待太久。 :/ – Rodrigue
這個問題只是一個訪問錯誤,我認爲。 WAMP有可能無法訪問自己的域名嗎?我在本地主機上運行這個文件 – Rodrigue