Check internet connection in PHP
In this article, we will discuss various methods in PHP to check the internet is present or not. We are going to create the scripts using predefined as well as user-defined methods to check internet connection in PHP.
How to check internet connection in PHP with predefined methods?
PHP offers a predefined method known as connection_status() that returns the state of the internet connection such as-
- CONNECTION_NORMAL
- CONNECTION_ABORTED
- CONNECTION_TIMEOUT etc.
Let us create the script using connection_status() method,
<?php //Checking internet connection status with predefined function switch (connection_status()) { case CONNECTION_NORMAL: $msg = 'You are connected to internet.'; break; case CONNECTION_ABORTED: $msg = 'No Internet connection'; break; case CONNECTION_TIMEOUT: $msg = 'Connection time-out'; break; case (CONNECTION_ABORTED & CONNECTION_TIMEOUT): $msg = 'No Internet and Connection time-out'; break; default: $msg = 'Undefined state'; break; } //display connection status echo $msg; ?>
Output:-
You are connected to internet.
How to check internet connection with user-defined methods?
This is the less effective way than the predefined methods and it involves the methods that use the ping methods to determine whether the internet connection is available or not. It usually tries to access a website and decide the status of the internet on the basis of that.
Let us create a PHP script using @fsockopen () method,
<?php //userdefined function for checking internet function check_internet($domain) { $file = @fsockopen ($domain, 80);//@fsockopen is used to connect to a socket return ($file); } //test with a website $domain="http://170.187.134.184"; //verify whether the internet is working or not if (check_internet($domain)) { echo "You are connected to the internet."; } else { echo "You seem to be offline. Please check your internet connection."; } ?>
Output:-
You are connected to the internet.
Let us create another PHP script using @fopen() method,
<?php //checking connection with @fopen if ( @fopen("http://170.187.134.184", "r") ) { print "You are connected to the internet."; } else { print "You seem to be offline. Please check your internet connection."; } ?>
Output:-
You are connected to the internet.
In the above ways, we can determine whether the internet connection is available or not usning PHP. If you have any doubt comment below.
See also,
I tried to use this code but when I try to open the page without internet connection. It says, no internet
Hello. I tried this, my internet is on but i keep getting the message for no internet connection