1

I'm using PHP file_get_contents to read text file data.

Assuming I have 2 IP Address, 1 online and 1 offline:

192.168.180.181 - Online
192.168.180.182 - Offline

And the PHP

$fileAccept = file_get_contents("\\\\192.168.180.181\\Reports\\".$dModel['MODEL_NAME'].$source."\\Accept\\Accept_".$dDtl['MODEL_CODE']."_".$dateCode."_".$dDtl['TS_CODE'].".txt");

As We Know IP Address 192.168.180.182 is offline, then I tried to run the code. And result the page always loading.

My question, how can I prevent it maybe first need to check the IP is alive or not, if alive then can continue to next step.

Maybe something like this:

if(IP IS OFFLINE)
{
    echo "do not do anything";
}
else
{
    echo "do something";
}
HiDayurie Dave
  • 1,791
  • 2
  • 17
  • 45

2 Answers2

0

you can try something like that

$scc = stream_context_create(array('http'=>
    array(
        'timeout' => 120,  //120 seconds 
    )
));
$url = "http://192.168.180.181/....";
$handle =  file_get_contents('$url, false, $scc);

you can create two handles and check whether is ok with if statement, of course you can change the timeout to suites you

Update: if accessing file locally you can check this stream_set_timeout() function , the documentation is here

Mohammed Omer
  • 1,168
  • 1
  • 10
  • 17
0

This solution is based on pinging the IP you need to check

class IPChecker{

    public static function isIPOnline($ip){

        switch (SELF::currentOS()){
            case "windows":
                $arg = "n";
                break;
            case "linux":
                $arg = "c";
                break;
            default: throw new \Exception('unknown OS');
        }

        $result = "";
        $output = [];
        // to debug errors add 2>&1 to the command to fill $output
        // https://stackoverflow.com/questions/16665041/php-why-isnt-exec-returning-output
        exec("ping -$arg 2 $ip " , $output, $result);
        // if 0 then the there is no errors like "Destination Host Unreachable"
        if ($result === 0) return true;
        return false;
    }


    public static function currentOS(){
        if(strpos(strtolower(PHP_OS), "win") !== false) return 'windows';
        elseif (strpos(strtolower(PHP_OS), "linux") !== false) return 'linux';
        //TODO: extend other OSs here
        else return 'unknown';

    }

}

usage example

var_dump( IPChecker::isIPOnline("192.168.180.181") );// should outputs bool(true) 
var_dump( IPChecker::isIPOnline("192.168.180.182") );// should outputs bool(false) 

I have used these answers (1, 2) in my answer

Accountant م
  • 6,975
  • 3
  • 41
  • 61