Skip to content
Advertisement

file_get_contents() Timeout in php

I know php doesn’t give timeout option since it is running from server side. But my logic needs timeout. Please solve this case

My 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");
}

my 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>

This javascript is not working. and obviously delay will happen in server code and i cannot watch it from client side.

so this is what i want. need to terminate submission process (from submit to rendering next page) if my file_get_contents() function is not responding for long.

Note: Please dont ask me to use curl, Because i am instructed to not use curl. and i cant get it in client side

Advertisement

Answer

The default value for a timeout in file_get_contents() is 60 seconds. You can change this value through the default_socket_timeout setting. It’s also doable in your code:

ini_set('default_socket_timeout', 2); // 2 seconds
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement