I have the following function that I doesn't work so far. I would like to ping an IP address and then to echo whether the IP is alive or not.
function pingAddress($ip){
$pingresult = shell_exec("start /b ping $ip -n 1");
$dead = "Request timed out.";
$deadoralive = strpos($dead, $pingresult);
if ($deadoralive == false){
echo "The IP address, $ip, is dead";
} else {
echo "The IP address, $ip, is alive";
}
}
When I call this function using the example:
pingAddress("127.0.0.1")
The echo result is always 'dead' - no matter what.
Could someone please help me where I'm going wrong?
And/OR is there a better method of doing this with the same result?
Many thanks.
Update: Have amended code to include the double quotes but still getting the same (incorrect) results.
NOTE: Solution below does not work on Windows. On linux exec a "which ping" command from the console, and set command path (of the suggested exec call) accordingly
I think you want to check the exit status of the command, whereas shell_exec gives you full output (might be dangerous shall command output change from command version to version. for some reason). Moreover your variable $ip is not interpreted within single quotes. You'd have to use double ones "". That might be the only thing you need to fix in order to make it work.
But I think following code can be more "portable". IMHO it is in fact better to catch the exit status, rather than trying to parse result string. IMHO it's also better to specify full path to ping command.
<?php
function pingAddress($ip) {
$pingresult = exec("/bin/ping -n 3 $ip", $outcome, $status);
if (0 == $status) {
$status = "alive";
} else {
$status = "dead";
}
echo "The IP address, $ip, is ".$status;
}
pingAddress("127.0.0.1");
This also did not work for me in Wordpress. I also tried -t and -n and other ways, but did not work. I used,
function pingAddress($ip) {
$pingresult = exec("/bin/ping -c2 -w2 $ip", $outcome, $status);
if ($status==0) {
$status = "alive";
} else {
$status = "dead";
}
$message .= '<div id="dialog-block-left">';
$message .= '<div id="ip-status">The IP address, '.$ip.', is '.$status.'</div><div style="clear:both"></div>';
return $message;
}
// Some IP Address
pingAddress("192.168.1.1");
This worked perfectly for me, finally.
I referred this from http://www.phpscriptsdaily.com/php/php-ping/
Hope this will help
Well I want to modify this as it is working fine on my localhost but not on my live server
For live server, I got another thing which now works for both local as well as live.
$fp = fSockOpen($ip,80,$errno,$errstr,1);
if($fp) { $status=0; fclose($fp); } else { $status=1; }
Then I show the Server is up for 0 and down for 1.
This works perfectly for me. I got this from Ping site and return result in PHP Thanks #karim79
I have developed the algorithm to work with heterogeneous OS, both Windows and Linux.
Implement the following class:
<?php
class CheckDevice {
public function myOS(){
if (strtoupper(substr(PHP_OS, 0, 3)) === (chr(87).chr(73).chr(78)))
return true;
return false;
}
public function ping($ip_addr){
if ($this->myOS()){
if (!exec("ping -n 1 -w 1 ".$ip_addr." 2>NUL > NUL && (echo 0) || (echo 1)"))
return true;
} else {
if (!exec("ping -q -c1 ".$ip_addr." >/dev/null 2>&1 ; echo $?"))
return true;
}
return false;
}
}
$ip_addr = "151.101.193.69"; #DNS: www.stackoverflow.com
if ((new CheckDevice())->ping($ip_addr))
echo "The device exists";
else
echo "The device is not connected";
i just wrote a very fast solution by combining all knowledge gain above
function pinger($address){
if(strtolower(PHP_OS)=='winnt'){
$command = "ping -n 1 $address";
exec($command, $output, $status);
}else{
$command = "ping -c 1 $address";
exec($command, $output, $status);
}
if($status === 0){
return true;
}else{
return false;
}
}
this works fine for me..
$host="127.0.0.1";
$output=shell_exec('ping -n 1 '.$host);
echo "<pre>$output</pre>"; //for viewing the ping result, if not need it just remove it
if (strpos($output, 'out') !== false) {
echo "Dead";
}
elseif(strpos($output, 'expired') !== false)
{
echo "Network Error";
}
elseif(strpos($output, 'data') !== false)
{
echo "Alive";
}
else
{
echo "Unknown Error";
}
For Windows Use this class
$host = 'www.example.com';
$ping = new Ping($host);
$latency = $ping->ping();
if ($latency !== false) {
print 'Latency is ' . $latency . ' ms';
}
else {
print 'Host could not be reached.';
}
https://github.com/geerlingguy/Ping
Based on the great answer of #tiamiyu-saheed-oluwatosin I wrote this small function in shorthand if/else (ternary) style, working on both Windows and Linux, to check if a second PHP server is up and running in my LAN.
function running($ip) {
exec("ping -{strtolower(PHP_OS)=='winnt'?'n':'c'} 1 $ip", $out, $res);
return ($res === 0 ? true : false);
}
Use :
if(running('192.168.1.20') {
// execute some code...
}
This works fine with hostname, reverse IP (for internal networks) and IP.
function pingAddress($ip) {
$ping = exec("ping -n 2 $ip", $output, $status);
if (strpos($output[2], 'unreachable') !== FALSE) {
return '<span style="color:#f00;">OFFLINE</span>';
} else {
return '<span style="color:green;">ONLINE</span>';
}
}
echo pingAddress($ip);
Do check the man pages of your ping command before trying some of these examples out (always good practice anyway). For Ubuntu 16 (for example) the accepted answer doesn't work as the -n 3 fails (this isn't the count of packets anymore, -n denotes not converting the IP address to a hostname).
Following the request of the OP, a potential alternative function would be as follows:
function checkPing($ip){
$ping = trim(`which ping`);
$ll = exec($ping . '-n -c2 ' . $ip, $output, $retVar);
if($retVar == 0){
echo "The IP address, $ip, is alive";
return true;
} else {
echo "The IP address, $ip, is dead";
return false;
}
}
This is work with me:
<?php
class CheckDevice {
public function myOS(){
if (strtoupper(substr(PHP_OS, 0, 3)) === (chr(87).chr(73).chr(78)))
return true;
return false;
}
public function ping($ip_addr){
if ($this->myOS()){
if (!exec("ping -n 1 -w 1 ".$ip_addr." 2>NUL > NUL && (echo 0) || (echo 1)"))return true;
} else {
if (!exec("ping -q -c1 ".$ip_addr." >/dev/null 2>&1 ; echo $?"))
return true;
}return false;
}
}
$ip_addr = "192.168.1.1";
if ((new CheckDevice())->ping($ip_addr))
echo "The device exists";
else
echo "The device is not connected";
I use this function :
<?php
function is_ping_address($ip) {
exec('ping -c1 -w1 '.$ip, $outcome, $status);
preg_match('/([0-9]+)% packet loss/', $outcome[3], $arr);
return ( $arr[1] == 100 ) ? false : true;
}
Related
i have a question about Sockets in PHP. My Environment Looks like follows:
one Server VM with Ubuntu 22.04 , and one VM with Windows 10. On The net is Global Cache IP2SL Adapter, on that interface is an Monitor with serial Line connected to this IP2SL.
The Goal should be , to send HEX Codes to the IP2SL which will be send to the Monitor. Some of These Codes have an Answer i.e. some Parameters like Brighness or Situation. In The end , on The Ubuntu is an Website where u can read and change those values . Therefore i've build some small testscripts to Check the Communication. To Monitor the line i use Wireshark, and both VM Linux and Windows run in a Parallels Environment on a Mac.
The Problem:
Did i send the hex code from windows to The IP2SL Adapter, anything looks fine, the command where send to the Monitor and the Monitor answer as expected. Did i send the same via php the command where send , and The Monitor Works with it as expected, if the commmand has no answer, i.e. PowerOn/Poweroff working like a charm, but if the Monitor should send an answer like brightness : XX% there come an "504 gateway TimeOut" After 60s on the Ubuntu System . did i do the same with IP2SL test App , the answer is correctly. In Wireshark is the Communication as expected. my php code Looks like follows
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
$port = '4999';
$adr = "192.168.100.34";
$sendStr = array('E5', 'TARGET', '20', '86');//hexadecimal data
$target = "05";
function makeValue($v)
{
return pack('H*',dechex($v));
}
function toSend($adr,$port,$target,$cmd)
{
ob_implicit_flush();
// find target
for($i=0;$i < count($cmd);$i++)
{
if($cmd[$i] === "TARGET")
{
$cmd[$i] = hexdec($target);
}
else
{
$cmd[$i] = hexdec($cmd[$i]);
}
}
// build the CRC
$cmd[] = hexdec('FF') - array_sum($cmd) & hexdec('FF');
//var_dump($cmd);
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
//socket_set_nonblock($socket);
if ($socket === false) {
echo "socket_create() fehlgeschlagen: Grund: " . socket_strerror(socket_last_error()) . "\n";
} else {
echo "Socket erstellt OK.\r\n";
}
echo "Versuche, zu '$adr' auf Port '$port' zu verbinden ...";
$result = socket_connect($socket, $adr, $port);
if ($result === false) {
echo "socket_connect() fehlgeschlagen.\nGrund: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
echo "Socket verbunden OK.\r\n";
}
$chars = array_map('makeValue',$cmd);
$out = join($chars);
$length = strlen($out);
//var_dump($out);
if(socket_write($socket, $out,$length))
{
usleep(25000);
$input = stream_get_contents($socket,1024);
socket_close($socket);
var_dump($input);
}
//socket_close($socket);
/*
if($input === FALSE || strcmp($input,'') == 0) {
$code = socket_last_error($socket);
socket_clear_error($socket);
socket_close($socket);
} else {
echo "Answer : ". bin2hex($input);
socket_close($socket);
}
*/
}
toSend($adr,$port,$target,$sendStr);
?>
Solution: The Solution is the array_map function 'makeValue'. The php pack command has an Format 'h*' and 'H*' , if the value is an Single Byte , the 'H*' converts it to the higher nibble , so the value '7' will Converted to '0x70'
function makeValue($v)
{
if(strlen($v)>1)
{
return pack('H*',dechex($v));
}
return pack('h*',dexhex($v));
}
this Solves the Problem
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";
}
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
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
I wanna run this with multiple IP and check if IPs are alive, unreachable or request time-out. I could not point out where I got mistake. I ran this without using loop and it works fine, but won't work for multiple IPs with for-loop. Help will be appreciated =)
for ($ipa=100; $ipa <= 110; $ipa++){
$ip = "192.168.254.{$ipa}";
exec ("ping -n 1 -w 1 $ip && exit", $ping_output);
if(preg_match("/TTL/i", $ping_output[2])) {
echo "{$ip} is On <br/>";
} else if("unreachable"){
echo "{$ip} is unreachable <br/>";
} else if("Request"){
echo "{$ip} is Off <br/>";
}
}
Looking at -n switch you are running this on Windows. There are some caveats running exec on Windows but since it worked once I won't go there. The other thing is that you need to unset $ping_output each time so the script uses the most recent data. Otherwise exec will just append data to this array. Finally those else if clauses will always return true.
It will help if you post some output from the var_dump line to see if there was an error running ping with a specific IP.
Here is my suggestion for this script. I have changed the preg_match to stripos which is much faster way to check if a substring is present.
for ($ipa=100; $ipa <= 110; $ipa++){
$ip = "192.168.254.".$ipa;
$ping_output=array();
exec ("ping -n 1 -w 1 $ip 2>&1", $ping_output, $return_val);
echo $ip." -> ".$return_val."<br/>".implode('<br/>',$ping_output).'<br/>';
if(stripos($ping_output[2],"TTL")!==false) {
echo $ip." is On <br/>";
} else if(stripos($ping_output[2],"unreachable")!==false){
echo $ip." is unreachable <br/>";
} else if(stripos($ping_output[2],"request")!==false){
echo $ip." is Off <br/>";
}
}
You can rite your ips into a text file and then ping ips by using that file like;
for ($ipa=100; $ipa <= 110; $ipa++){
$ip = "192.168.254.{$ipa}";
exec ("ping -n 1 -w 1 $ip 2>&1", $ping_output, $return_val);
var_dump(array($ping_output, $return_val));
if(preg_match("/TTL/i", $ping_output[2])) {
echo "{$ip} is On <br/>";
} else if("unreachable"){
echo "{$ip} is unreachable <br/>";
} else if("Request"){
echo "{$ip} is Off <br/>";
}
}
How can you mimic a command line run of a script with arguements inside a PHP script? Or is that not possible?
In other words, let's say you have the following script:
#!/usr/bin/php
<?php
require "../src/php/whatsprot.class.php";
function fgets_u($pStdn) {
$pArr = array($pStdn);
if (false === ($num_changed_streams = stream_select($pArr, $write = NULL, $except = NULL, 0))) {
print("\$ 001 Socket Error : UNABLE TO WATCH STDIN.\n");
return FALSE;
} elseif ($num_changed_streams > 0) {
return trim(fgets($pStdn, 1024));
}
}
$nickname = "WhatsAPI Test";
$sender = ""; // Mobile number with country code (but without + or 00)
$imei = ""; // MAC Address for iOS IMEI for other platform (Android/etc)
$countrycode = substr($sender, 0, 2);
$phonenumber=substr($sender, 2);
if ($argc < 2) {
echo "USAGE: ".$_SERVER['argv'][0]." [-l] [-s <phone> <message>] [-i <phone>]\n";
echo "\tphone: full number including country code, without '+' or '00'\n";
echo "\t-s: send message\n";
echo "\t-l: listen for new messages\n";
echo "\t-i: interactive conversation with <phone>\n";
exit(1);
}
$dst=$_SERVER['argv'][2];
$msg = "";
for ($i=3; $i<$argc; $i++) {
$msg .= $_SERVER['argv'][$i]." ";
}
echo "[] Logging in as '$nickname' ($sender)\n";
$wa = new WhatsProt($sender, $imei, $nickname, true);
$url = "https://r.whatsapp.net/v1/exist.php?cc=".$countrycode."&in=".$phonenumber."&udid=".$wa->encryptPassword();
$content = file_get_contents($url);
if(stristr($content,'status="ok"') === false){
echo "Wrong Password\n";
exit(0);
}
$wa->Connect();
$wa->Login();
if ($_SERVER['argv'][1] == "-i") {
echo "\n[] Interactive conversation with $dst:\n";
stream_set_timeout(STDIN,1);
while(TRUE) {
$wa->PollMessages();
$buff = $wa->GetMessages();
if(!empty($buff)){
print_r($buff);
}
$line = fgets_u(STDIN);
if ($line != "") {
if (strrchr($line, " ")) {
// needs PHP >= 5.3.0
$command = trim(strstr($line, ' ', TRUE));
} else {
$command = $line;
}
switch ($command) {
case "/query":
$dst = trim(strstr($line, ' ', FALSE));
echo "[] Interactive conversation with $dst:\n";
break;
case "/accountinfo":
echo "[] Account Info: ";
$wa->accountInfo();
break;
case "/lastseen":
echo "[] Request last seen $dst: ";
$wa->RequestLastSeen("$dst");
break;
default:
echo "[] Send message to $dst: $line\n";
$wa->Message(time()."-1", $dst , $line);
break;
}
}
}
exit(0);
}
if ($_SERVER['argv'][1] == "-l") {
echo "\n[] Listen mode:\n";
while (TRUE) {
$wa->PollMessages();
$data = $wa->GetMessages();
if(!empty($data)) print_r($data);
sleep(1);
}
exit(0);
}
echo "\n[] Request last seen $dst: ";
$wa->RequestLastSeen($dst);
echo "\n[] Send message to $dst: $msg\n";
$wa->Message(time()."-1", $dst , $msg);
echo "\n";
?>
To run this script, you are meant to go to the Command Line, down to the directory the file is in, and then type in something like php -s "whatsapp.php" "Number" "Message".
But what if I wanted to bypass the Command Line altogether and do that directly inside the script so that I can run it at any time from my Web Server, how would I do that?
First off, you should be using getopt.
In PHP it supports both short and long formats.
Usage demos are documented at the page I've linked to. In your case, I suspect you'll have difficulty detecting whether a <message> was included as your -s tag's second parameter. It will probably be easier to make the message a parameter for its own option.
$options = getopt("ls:m:i:");
if (isset($options["s"] && !isset($options["m"])) {
die("-s needs -m");
}
As for running things from a web server ... well, you pass variables to a command line PHP script using getopt() and $argv, but you pass variables from a web server using $_GET and $_POST. If you can figure out a sensible way to map $_GET variables your command line options, you should be good to go.
Note that a variety of other considerations exist when taking a command line script and running it through a web server. Permission and security go hand in hand, usually as inverse functions of each other. That is, if you open up permissions so that it's allowed to do what it needs, you may expose or even create vulnerabilities on your server. I don't recommend you do this unless you'll more experienced, or you don't mind if things break or get attacked by script kiddies out to 0wn your server.
You're looking for backticks, see
http://php.net/manual/en/language.operators.execution.php
Or you can use shell_exec()
http://www.php.net/manual/en/function.shell-exec.php
How can I check if I'm connected to the internet from my PHP script which is running on my dev machine?
I run the script to download a set of files (which may or may not exist) using wget. If I try the download without being connected, wget proceeds to the next one thinking the file is not present.
<?php
function is_connected()
{
$connected = #fsockopen("www.example.com", 80);
//website, port (try 80 or 443)
if ($connected){
$is_conn = true; //action when connected
fclose($connected);
}else{
$is_conn = false; //action in connection failure
}
return $is_conn;
}
?>
You can always ping good 'ol trusty google:
$response = null;
system("ping -c 1 google.com", $response);
if($response == 0)
{
// this means you are connected
}
This code was failing in laravel 4.2 php framework with an internal server 500 error:
<?php
function is_connected()
{
$connected = #fsockopen("www.some_domain.com", 80);
//website, port (try 80 or 443)
if ($connected){
$is_conn = true; //action when connected
fclose($connected);
}else{
$is_conn = false; //action in connection failure
}
return $is_conn;
}
?>
Which I didn't want to stress myself to figure that out, hence I tried this code and it worked for me:
function is_connected()
{
$connected = fopen("http://www.google.com:80/","r");
if($connected)
{
return true;
} else {
return false;
}
}
Please note that: This is based upon the assumption that the connection to google.com is less prone to failure.
The accepted answer did not work for me. When the internet was disconnected it threw a php error. So I used it with a little modification which is below:
if(!$sock = #fsockopen('www.google.com', 80))
{
echo 'Not Connected';
}
else
{
echo 'Connected';
}
Why don't you fetch the return code from wget to determine whether or not the download was successful? The list of possible values can be found at wget exit status.
On the other hand, you could use php's curl functions as well, then you can do all error tracking from within PHP.
There are various factors that determine internet connection. The interface state, for example. But, regardles of those, due to the nature of the net, proper configuration does not meen you have a working connection.
So the best way is to try to download a file that you’re certain that exists. If you succeed, you may follow to next steps. If not, retry once and then fail.
Try to pick one at the destination host. If it’s not possible, choose some major website like google or yahoo.
Finally, just try checking the error code returned by wget. I bet those are different for 404-s and timeouts. You can use third parameter in exec call:
string exec ( string $command [, array &$output [, int &$return_var ]] )
/*
* Usage: is_connected('www.google.com')
*/
function is_connected($addr)
{
if (!$socket = #fsockopen($addr, 80, $num, $error, 5)) {
echo "OFF";
} else {
echo "ON";
}
}
Also note that fopen and fsockopen are different. fsockopen opens a socket depending on the protocol prefix. fopen opens a file or something else e.g file over HTTP, or a stream filter or something etc. Ultimately this affects the execution time.
You could ping to a popular site or to the site you're wgetting from (like www.google.nl) then parse the result to see if you can connect to it.
<?php
$ip = '127.0.0.1'; //some ip
exec("ping -n 4 $ip 2>&1", $output, $retval);
if ($retval != 0) {
echo "no!";
}
else
{
echo "yes!"; }
?>
Just check the result of wget. A status code of 4 indicates a network problem, a status code of 8 indicates a server error (such as a 404). This only works if you call wget for each file in sequence, rather than once for all the files.
You can also use libcurl with PHP, instead of calling wget. Something like:
foreach (...) {
$c = curl_init($url);
$f = fopen($filepath, "w")
curl_setopt($c, CURLOPT_FILE, $f);
curl_setopt($c, CURLOPT_HEADER, 0);
if (curl_exec($c)) {
if (curl_getinfo($c, CURLINFO_HTTP_CODE) == 200) {
// success
} else {
// 404 or something, delete file
unlink($filepath);
}
} else {
// network error or server down
break; // abort
}
curl_close($c);
}
This function handles what you need
function isConnected()
{
// use 80 for http or 443 for https protocol
$connected = #fsockopen("www.example.com", 80);
if ($connected){
fclose($connected);
return true;
}
return false;
}
You can use this by adding this inside a class:
private $api_domain = 'google.com';
private function serverAliveOrNot()
{
if($pf = #fsockopen($this->api_domain, 443)) {
fclose($pf);
$_SESSION['serverAliveOrNot'] = true;
return true;
} else {
$_SESSION['serverAliveOrNot'] = false;
return false;
}
}
+1 on Alfred's answer, but I think this is an improved version:
function hasInternet()
{
$hosts = ['1.1.1.1', '1.0.0.1', '8.8.8.8', '8.8.4.4'];
foreach ($hosts as $host) {
if ($connected = #fsockopen($host, 443)) {
fclose($connected);
return true;
}
}
return false;
}
My reasons:
This pings more than 1 server and will only fail if all 4 fails
If first host works, it will return true immediately
IP addresses are from CloudFlare and Google DNS which basically controls most of the internet and always online
1.1.1.1 is rated the fastest DNS resolver (Source)
Only doubt I have is to use port 443 or 80? Suggestions would be appreciated! :)
Very PHP way of doing it is
<?php
switch (connection_status())
{
case CONNECTION_NORMAL:
$txt = 'Connection is in a normal state';
break;
case CONNECTION_ABORTED:
$txt = 'Connection aborted';
break;
case CONNECTION_TIMEOUT:
$txt = 'Connection timed out';
break;
case (CONNECTION_ABORTED & CONNECTION_TIMEOUT):
$txt = 'Connection aborted and timed out';
break;
default:
$txt = 'Unknown';
break;
}
echo $txt;
?>
https://www.w3schools.com/php/func_misc_connection_status.asp