Php socket read with timeout

Php — fgets() reading with socket, still not working properly

I’ve spent a lot of time on this fgets() problems without any success until now. I’m receiving data from different sources through a HTTP socket. It worked fine until now that I have a lot more different sources. My goal is just to get rid of the execution timeout of php, just know that it timed out after 15 seconds but go on with the next source. Here is my small piece of code:

//This is just from php.net, found out that it works pretty good $time = time(); while (!($temp = fsockopen($host, $port, $errNo, $errMessage, $timeout))) < if ((time() - $time) >= $timeout) < socket_close($temp); return false; >sleep(1); > //If PHP returns an error if (!($temp)) < echo 'Socket could not be opened.
'; return false; > $return = ""; if (!fwrite($temp, $out)) < print_r(error_get_last()); return false; >//Timeout set to 15 seconds stream_set_blocking($temp, 0); $start = time(); while ((time() < ($start + 15))) < //(Last lines always finishes like this) if (substr(trim($return),-9) == '"id":"1">') < break; >else < $return .= fgets($temp, 512); >> fclose($temp);

After some testing I found out that a non-blocking socket gives way better results for this code, however it is still blocking after data has been received for 4 sources. (I tried to change the order so it is not source-dependent) I tried to use stream_set_timeout($temp) and check the state of the flag in the loop but it doesn’t change a thing. EDIT: I forgot to mention it, but the script is stopping (PHP execution timeout of 30 seconds) at the line with fgets(). Any clues? Cheers!

Читайте также:  Умножение в питоне это

Источник

Make PHP socket_connect timeout

I have a small application I created to analyze the network connection. It runs from a browser and connects to a local PHP/Apache server. It then asks PHP to send a ping packet through a raw socket. THe problem is that if the host I am trying to ping isn’t alive or won’t answer to pings, we never get an answer from the server. I beleave the socket request lives until apache is restarted. I have been getting mixed results from my application lately and I am blaming apache using too many sockets. Currently I have set the AJAX call’s timeout and I was happy with it. But I really need to make PHP do the timeouting so that I won’t have 500,000 sockets open to an unreachable host. Some sample code:

$sockconn = @socket_connect($socket, $target, null); if(!$sockconn)

This is the function that won’t timeout. I need to get it to timeout. Also PHP script execution time DOES NOT affect sockets. I am clueless.

Seriously, use fsockopen() instead. It makes a lot of things a lot easier, it is more readily available (it is a core function that must be explicitly disabled, whereas the sockets extension must be explicitly enabled) and the 5th argument lets you define the connect timeout on a per-call basis.

In theory yes (although with the more advanced stream_socket_* functions rather than fsockopen() ). In practice it would be a massive PITA. I sort of assumed you would be dealing with TCP, most of the time that’s what people are doing. If what you want is a PHP-driven ICMP echo implementation, though, I’ve already done that. take a look at this: download.networkm.net/code/php/class.ping.1.0.tar.gz (note that it was written for PHP4, and when my OO skills left. something to be desired, but it does work I have used it a couple of times)

Читайте также:  Php mail list server

Источник

stream_set_timeout

Sets the timeout value on stream , expressed in the sum of seconds and microseconds .

When the stream times out, the ‘timed_out’ key of the array returned by stream_get_meta_data() is set to true , although no error/warning is generated.

Parameters

The seconds part of the timeout to be set.

The microseconds part of the timeout to be set.

Return Values

Returns true on success or false on failure.

Examples

Example #1 stream_set_timeout() example

$fp = fsockopen ( «www.example.com» , 80 );
if (! $fp ) echo «Unable to open\n» ;
> else

fwrite ( $fp , «GET / HTTP/1.0\r\n\r\n» );
stream_set_timeout ( $fp , 2 );
$res = fread ( $fp , 2000 );

$info = stream_get_meta_data ( $fp );
fclose ( $fp );

if ( $info [ ‘timed_out’ ]) echo ‘Connection timed out!’ ;
> else echo $res ;
>

Notes

Note:

This function doesn’t work with advanced operations like stream_socket_recvfrom() , use stream_select() with timeout parameter instead.

This function was previously called as set_socket_timeout() and later socket_set_timeout() but this usage is deprecated.

See Also

User Contributed Notes 11 notes

In case anyone is puzzled, stream_set_timeout DOES NOT work for sockets created with socket_create or socket_accept. Use socket_set_option instead.

Instead of:
stream_set_timeout ( $socket , $sec , $usec );
?>

Use:
socket_set_option ( $socket , SOL_SOCKET , SO_RCVTIMEO , array( ‘sec’ => $sec , ‘usec’ => $usec ));
socket_set_option ( $socket , SOL_SOCKET , SO_SNDTIMEO , array( ‘sec’ => $sec , ‘usec’ => $usec ));
?>

If the timeout fails, because the server remains completely silent, one may have to add stream_select() to make the timeout work. This may be much more efficient that a non-blocking reading operation.

// Handling of «traditional» timeout
$info = stream_get_meta_data ( $c );
if ( $info [ ‘timed_out’ ]) trigger_error ( ‘Timeout’ );
break;
>
>
?>

Background: We had issues with a SMTP server that was addresses unencrypted while expecting TLS encryption. The stream_set_timeout() alone did not work as expected and the script hung for an hour or more.

Here is a working example for loops:

// Timeout in seconds
$timeout = 5 ;

$fp = fsockopen ( «www.server.com» , 80 , $errno , $errstr , $timeout );

if ( $fp ) <
fwrite ( $fp , «GET /file.php HTTP/1.0\r\n» );
fwrite ( $fp , «Host: www.server.com\r\n» );
fwrite ( $fp , «Connection: Close\r\n\r\n» );

stream_set_blocking ( $fp , TRUE );
stream_set_timeout ( $fp , $timeout );
$info = stream_get_meta_data ( $fp );

if ( $info [ ‘timed_out’ ]) <
echo «Connection Timed Out!» ;
> else <
echo $data ;
>
>
?>

Another note alread states that blocking-reads may be an issue, if the counterpart responds very slowly — or not at all. The stream timeout may not work as expected in such a situation.

However, php.net provides very little information on how to use non-blocking reading operations. Here’s a code sample:

stream_set_timeout ( $c , $timeout );
$data = » ;
while ( is_resource ( $c ) && ! feof ( $c )) // Use non-blocking reading for first loop
if (( $data === » ) and ( $timeout > 0 )) stream_set_blocking ( $c , false );
$endtimeOut = time () + $timeout ;
$str = » ;
while (( time () < $endtimeOut ) and ( strlen ( $str ) < 515 ) and ! feof ( $c )) sleep ( 1 ); // Note: This may require tuning
$str .= fgets ( $c , 515 );
>
// Handling first-read timeout
if ( time () >= $endtimeOut ) trigger_error ( ‘Timeout’ , E_USER_WARNING );
break;
>
stream_set_blocking ( $c , true );
> else $str = fgets ( $c , 515 );
>
$data .= $str ;

// Handling of «traditional» timeout
$info = stream_get_meta_data ( $c );
if ( $info [ ‘timed_out’ ]) trigger_error ( ‘Timeout’ , E_USER_WARNING );
break;
>
>
?>

Источник

PHP socket_set_timeout() Function: Everything You Need to Know

As a PHP developer, you may need to set a timeout for a socket to avoid lengthy waits and potential resource waste. The socket_set_timeout() function is a built-in function in PHP that allows you to set a timeout for a socket. In this article, we will take an in-depth look at the socket_set_timeout() function and its usage.

What is the socket_set_timeout() Function?

The socket_set_timeout() function is a PHP built-in function that allows you to set a timeout for a socket.

How to Use the socket_set_timeout() Function

Using the socket_set_timeout() function is straightforward. Here is the syntax of the function:

socket_set_timeout(resource $socket, int $seconds, int $microseconds);

The function takes three parameters:

  • $socket: The socket to set the timeout for.
  • $seconds: The number of seconds for the timeout.
  • $microseconds: The number of microseconds for the timeout.

Here is an example of how to use the socket_set_timeout() function to set a timeout for a socket:

 $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_timeout($socket, 5, 0);

In this example, we use the socket_create() function to create a new socket, and then use the socket_set_timeout() function to set the timeout for the socket to 5 seconds.

Conclusion

The socket_set_timeout() function is a useful tool for setting a timeout for a socket in your PHP web application. By understanding the syntax and usage of the function, you can easily set a timeout for a socket to avoid lengthy waits and potential resource waste. We hope this article has been informative and useful in understanding the socket_set_timeout() function in PHP.

Источник

Оцените статью