Vic*_*cky 2 javascript php timeout file-get-contents
我知道 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");
}
Run Code Online (Sandbox Code Playgroud)
我的 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>
Run Code Online (Sandbox Code Playgroud)
这个 javascript 不起作用。显然延迟会发生在服务器代码中,我无法从客户端观看。
所以这就是我想要的。如果我的file_get_contents()
函数长时间没有响应,需要终止提交过程(从提交到呈现下一页)。
注意:请不要让我使用 curl,因为我被指示不要使用 curl。我不能在客户端得到它
小智 5
file_get_contents() 中超时的默认值为 60 秒。您可以通过 default_socket_timeout 设置更改此值。它在您的代码中也是可行的:
ini_set('default_socket_timeout', 2); // 2 seconds
Run Code Online (Sandbox Code Playgroud)