Cara menggunakan php default socket timeout
Timeouts are a rarely discussed topic and neglected in many applications, even though they can have a huge effect on your site during times of high load and when dependent services are slow. For microservice architectures timeouts are important to avoid cascading failures when a service is down. Show The default socket timeout in PHP is 60 seconds. HTTP requests performed with for example Since the socket/stream wait time is not included in PHPs max execution time you are in line for a surprise when requests take up to 30+60=90 seconds of your webservers precious processing queue before getting aborted. Timeouts are scary, because you don’t know in what state you have left an operation when aborting. But in case of HTTP requests it is usually easy as a client to decide what to do:
And configuring timeouts has other upsites:
Setting the default timeoutBefore doing anything else, you should decrease the default timeout early in your code to a value between 5 and 10 seconds:
You should check your monitoring system (for example Tideways) for clues what a regular HTTP call duration is for calls to internal or third party systems. If you have many different internal or third-party services in place, then it makes sense to configure individual timeouts based on their usual latency. A thorough setup defines maximum limits for each internal and third party service and then encodes them in HTTP calls. Configuring the timeout for individual file_get_contents/fopen callsIn stream based calls you can configure individual timeouts using stream contexts. This applies to for example
Be aware the timeout handling of streams seems not very accurate and requests can still take longer than you configured, especially when you go below 1 second. Configuring the timeout for DOMDocument::loadIn general you should not use the
This affects all HTTP calls that PHP does through libxml. Configuring the timeout for SOAPClientThe SOAPClient class does not use the PHP stream
API for historical reasons. This means that timeout configuration works slightly different. Setting the Instead you can either set the
Configuring the timeout for cURL extensionIf you want to have more control about HTTP requests than with PHPs built in stream support there is no way around the cURL extension. We have much better timeout control with cURL, with two settings one for the connection timeout and one for the maximum execution time:
If you want to be more strict and abort on a millisecond level, then you can alternatively use One important thing to remember is cURL has an indefinite timeout by default and does not obey the |