Does file_get_contents() have a timeout setting?
Yes, the file_get_contents function in PHP does have a timeout setting. You can specify the number of seconds that the function should wait for a connection to be established and for data to be received before timing out. You can do this using the stream_context_create
function to create a stream context and setting the http
or ssl
timeout options in the context, and then passing this context as the third argument to file_get_contents. Here is an example:
<?php
$options = [
'http' => [
'timeout' => 3, // 3 seconds
],
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true,
],
];
$context = stream_context_create($options);
$contents = file_get_contents('https://example.com', false, $context);
Watch a video course
Learn object oriented PHP
This will set the timeout for the file_get_contents function to 3 seconds. If a connection cannot be established or if data cannot be received within this time, the function will return a timeout error.