Related
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 have a php function called getServerAddres() and I am trying to execute the exec() from the web browser. I understand this is not the proper way of using the function, I was just a task to exploit a web server using remote code injection. Any help on how to do remote code injection using the exec() through the web browser would be greatly appreciated.
Lets say the login in screen is: https://www.10.10.20.161/test/
function getServerAddress() {
if(isset($_SERVER["SERVER_ADDR"]))
return $_SERVER["SERVER_ADDR"];
else {
// Running CLI
if(stristr(PHP_OS, 'WIN')) {
// Rather hacky way to handle windows servers
exec('ipconfig /all', $catch);
foreach($catch as $line) {
if(eregi('IP Address', $line)) {
// Have seen exec return "multi-line" content, so another hack.
if(count($lineCount = split(':', $line)) == 1) {
list($t, $ip) = split(':', $line);
$ip = trim($ip);
} else {
$parts = explode('IP Address', $line);
$parts = explode('Subnet Mask', $parts[1]);
$parts = explode(': ', $parts[0]);
$ip = trim($parts[1]);
}
if(ip2long($ip > 0)) {
echo 'IP is '.$ip."\n";
return $ip;
} else
; // to-do: Handle this failure condition.
}
}
} else {
$ifconfig = shell_exec('/sbin/ifconfig eth0');
preg_match('/addr:([\d\.]+)/', $ifconfig, $match);
return $match[1];
}
}
}
The php script came from the login.php file.
You dont seem to understand the exec function....
First thing, read the documentation here.
This function gets executed on the server side, and thus cannot be executed on the client side.
If what you want is the information of the host machine, then you can run the command there, and output the result.
Create this file: example.php, and enter this code:
<?php
echo exec('whoami');
?>
Now, upload this file to the host, and make a request:
www.YOURHOST.smg/example.php
And read the result
I'm wondering if it possible to create network layer packets (i.e. define my own IP headers) using PHP? It seems like socket_create with SOCK_RAW only lets you define the contents of the IP packet, not the headers itself.
Thanks in advance for your replies!
I was able to successfully create a socket using SOCK_RAW on Mac OS X, as long as I ran the script as root.
The example I used was taken from Jean Charles MAMMANA's ping.inc.php
I created a ping.php wrapper, and executed: sudo ping.php www.google.com.
Here's my ping.php wrapper:
<?php
$default_timeout = 15;
require("ping.inc.php");
if (count($argv) < 2) usage();
$timeout = count($argv) >= 3 ? intval($argv[2]) : $default_timeout;
$host = $argv[1];
$result = ping($host, $timeout);
if ($result < 0) {
echo "Error: " . $g_icmp_error . "\n";
} else {
echo "$result ms\n";
}
function usage() {
global $argv;
echo "Usage: {$argv[0]} <host> [timeout]\n";
die();
}
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;
}
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