Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
connection_status() function in PHP
The connection_status() function in PHP returns the status of the current connection between the server and client. This function is particularly useful for checking if a user has disconnected from a long-running script.
Syntax
connection_status()
Parameters
This function does not accept any parameters.
Return Value
The connection_status() function returns an integer representing the connection status bitfield −
0 - CONNECTION_NORMAL - connection is running normally
1 - CONNECTION_ABORTED - connection is aborted by user or network error
2 - CONNECTION_TIMEOUT - connection timed out
3 - CONNECTION_ABORTED & CONNECTION_TIMEOUT - both conditions occurred
Example
The following example demonstrates how to check the connection status and display appropriate messages −
<?php
switch (connection_status()) {
case CONNECTION_NORMAL:
$msg = 'Connection is in a normal state!';
break;
case CONNECTION_ABORTED:
$msg = 'Connection aborted!';
break;
case CONNECTION_TIMEOUT:
$msg = 'Connection timed out!';
break;
case (CONNECTION_ABORTED & CONNECTION_TIMEOUT):
$msg = 'Connection aborted and timed out!';
break;
default:
$msg = 'Status is unknown!';
break;
}
echo $msg;
?>
Connection is in a normal state!
Practical Use Case
This function is commonly used in long-running scripts to check if the client is still connected −
<?php
for ($i = 1; $i <= 100; $i++) {
if (connection_status() != CONNECTION_NORMAL) {
error_log("Client disconnected at iteration $i");
break;
}
// Simulate long-running task
sleep(1);
echo "Processing step $i...<br>";
flush();
}
?>
Conclusion
The connection_status() function is essential for monitoring client connections in long-running PHP scripts. It helps prevent unnecessary processing when clients disconnect and enables proper resource cleanup.
