簡體   English   中英

php中的file_get_contents()超時

[英]file_get_contents() Timeout in php

我知道 php 沒有提供超時選項,因為它是從服務器端運行的。 但我的邏輯需要超時。 請解決這個案例

我的 PHP: login.php :-

$forms_values = $_POST;
$url = "http://sample.com/sample?params=$forms_values";
$resp = file_get_contents($url);
// It takes much time if sample.com is down.
// so need to set time out here.
$response = json_decode($resp, true);
....
....
if ($response["auth"] == "yes"){
   header("index.php");
}

我的 html index.html :-

<form action="login.php" method="post" id="clientLogin">
    <div>
        <input id="username" placeholder="Email or Username" type="text" name="luser" size="30" value="">
    </div>
    <div>
        <input id="passwd" placeholder="Password" type="password" name="lpasswd" size="30" value="">
    </div>
<input class="btn" type="submit" value="Sign In">
</form>
<script type="text/javascript">
//This is not working. and obviously delay will happen in server code 
//and i cant get it in client side 

$(window).load(function () {
     var submit = false;
     $("#clientLogin").submit(function(e) {
         alert("me after 1000 mili seconds");
          setTimeout(function(){
              alert("me after 1000 mili seconds");
              submit = true;
              $("#clientLogin").submit(); // if you want            
          }, 15000);
          if(!submit)
              e.preventDefault();
     });
};
</script>

這個 javascript 不起作用。 顯然延遲會發生在服務器代碼中,我無法從客戶端觀看。

所以這就是我想要的。 如果我的file_get_contents()函數長時間沒有響應,則需要終止提交過程(從提交到呈現下一頁)。

注意:請不要讓我使用 curl,因為我被指示不要使用 curl。 我不能在客戶端得到它

file_get_contents() 中超時的默認值為 60 秒。 您可以通過 default_socket_timeout 設置更改此值。 它在您的代碼中也是可行的:

ini_set('default_socket_timeout', 2); // 2 seconds

將代碼放在腳本的開頭

ini_set('default_socket_timeout', 30); // 30 seconds

默認設置為 60 秒。

或者,考慮使用cURL

它提供 CURLOPT_CONNECTTIMEOUT 參數來指定嘗試建立連接時等待的時間量。

set_time_limit() 確實在全局運行,但可以在本地重置。

設置允許腳本運行的秒數。 如果達到,腳本將返回一個致命錯誤。 默認限制為 30 秒,如果存在,則為 php.ini 中定義的 max_execution_time 值。

調用時, set_time_limit() 從零重新啟動超時計數器。 換句話說,如果超時是默認的 30 秒,並且在腳本執行 25 秒后調用了諸如 set_time_limit(20) 之類的調用,則腳本將在超時前總共運行 45 秒。 我沒有測試過,但你可以在本地設置,離開時重置

<?php
set_time_limit(0);  // global setting

function doStuff()
{
    set_time_limit(10);   // limit this function
    //  stuff
    set_time_limit(10);   // give ourselves another 10 seconds if we want
    //  stuff
    set_time_limit(0);    // the rest of the file can run forever
}

// ....
sleep(900);
// ....
doStuff();  // only has 10 secs to run
// ....
sleep(900);
// ....

如果在 5 秒內沒有收到內容, $resp將為空


$ctx = stream_context_create(['http'=> ['timeout' => 5]]); // 5 seconds
$resp = file_get_contents($url,null,$ctx);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM