How to get the Round Trip Time in my PING using PHP - php

So i have this code that whenever an IP is ping able or up it'll choose the green line to appear on my screen and in reverse the red line. So what I am trying to do instead if the Round Trip Time of that IP is < 200 then it's green and when it's > 250 it's red . How can i do that?
Anyone help me. Thank you.
<?php
$page = $_SERVER['PHP_SELF'];
$sec = 5;
function pingAddress($TEST) {
$pingresult = exec("ping -c 1 $TEST", $output, $result);
if ($result == 0) {
echo "Ping successful!";
echo "<pre>Your ping: $TEST</pre>";
echo "<hr color = \"green\" width = 40%> GOOD";
} else {
echo "Ping unsuccessful!";
echo "<pre>Your ping: $TEST</pre>";
echo "<hr color = \"red\" width = 40%> BAD";
}
}
pingAddress("66.147.244.228");
?>
<html>
<head>
<meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">
</head>
<body>
</body>
</html>

The exec function is ok to use, but you should parse the contents of the output argument, after declaring it first as an array.
Even if you added -c 1 to only issue one ping, this is the recommended way of using exec.
define('RETRIES', 1);
define('PING_PATH', '/usr/bin/ping');
function pingAddress($IP)
{
$output = array();
exec(PING_PATH . " -c " . RETRIES . " $IP", $output);
// generic way, even for one line. You can also do -c 4,
// and preg_match will pick the first meaningful result.
$output_string = implode("; ", $output);
/// adapt the regular expression to the actual format of your implementation of ping
if (preg_match('/ time=\s+(\d+)ms/', $output_string, $bits)) {
$rt_time = (int)$bits[1];
if ($rt_time < 200) {
// green business
}
else if ($rt_time > 250) {
// red business
}
else {
// default handler business (or not...)
}
}
else {
echo "Hum, I didn't manage to parse the output of the ping command.", PHP_EOL;
}
}

Related

executing shell command PHP and raspberry pi

I am following : http://www.instructables.com/id/Simple- ... ur-Raspbe/
The objective is to switch ON and OFF Pins as guided in tutorial But
here i am not able to use : system(),exec() as it does not execute
commands in raspberry pi. Page is getting loaded accurately but when i
press buttons only image changes(ON/OFF) but no execution of commands.
I have well connected relays for my desired GPIO pin numbers
I am using Tools : PHP,Javascript,Lighttpd webserver and my device is Pi 3 model B with raspian Jessie installed.
So i have decided to use " shell_exec " to execute commands but after implementing it into
program there is no effect in my prgram and it displays nothing. Need help where i am doing wrong.
gpio.php
<?php
//This page is requested by the JavaScript, it updates the pin's status and then print it
//Getting and using values
$pin = array(4,17,18,27,22,23,24,25);
if (isset ( $_GET["pic"] )) {
$pic = strip_tags ($_GET["pic"]);
//test if value is a number
if ( (is_numeric($pic)) && ($pic <= 7) && ($pic >= 0) ) {
//set the gpio's mode to output
shell_exec("/usr/local/bin/gpio -g mode $pin[$pic] out");
//reading pin's status
shell_exec("/usr/local/bin/gpio -g read $pin[$pic] $status $return ");
//set the gpio to high/low
if ($status[0] == "0" ) { $status[0] = "1"; }
else if ($status[0] == "1" ) { $status[0] = "0"; }
shell_exec("/usr/local/bin/gpio -g write $pin[$pic] $status[0]");
//reading pin's status
shell_exec ("/usr/local/bin/gpio -g read $pin[$pic] $status $return");
//print it to the client on the response
echo($status[0]);
}
else { echo ("fail"); }
} //print fail if cannot use values
else { echo ("fail"); }
?>
index.php
<!DOCTYPE html>
<!--TheFreeElectron 2015, http://www.instructables.com/member/TheFreeElectron/ -->
<html>
<head>
<meta charset="utf-8" />
<title>Raspberry Pi Gpio</title>
</head>
<body style="background-color: black;">
<!-- On/Off button's picture -->
<?php
$val_array = array(0,0,0,0,0,0,0,0);
$pin = array(4,17,18,27,22,23,24,25);
//this php script generate the first page in function of the file
for ( $i= 0; $i<8; $i++) {
//set the pin's mode to output and read them
shell_exec("/usr/local/bin/gpio -g mode $pin[$pic] out");
shell_exec("/usr/local/bin/gpio -g read $i, $val_array[$i],$status $return ");
}
//for loop to read the value
$i =0;
for ($i = 0; $i < 8; $i++) {
//if off
if ($val_array[$i][0] == 0 ) {
echo ("<img id='button_".$i."' src='data/img/red/red_".$i.".jpg' onclick='change_pin (".$i.");'/>");
}
//if on
if ($val_array[$i][0] == 1 ) {
echo ("<img id='button_".$i."' src='data/img/green/green_".$i.".jpg' onclick='change_pin (".$i.");'/>");
}
}
?>
<!-- javascript -->
<script src="script.js"></script>
</body>
</html>
Thanks
Atila

PHP file_get_html on Pinterest - Some seriously weird behaviour

Trying to scrape a bit of basic account info from Pinterest pages (no I'm not scraping pins before I get accused of using this maliciously, it's simply a competitor research tool).
Some accounts work fine with file_get_html, others return completely blank objects and I can't figure out why. I've built the below test code with completely random pages of different sizes to try and do some testing... still no further forward.
It uses Simple HTML DOM and here is my test code trying to figure out why some aren't working.
$pinterestUrl1 = "https://uk.pinterest.com/sfashionality/";
$pinterestUrl2 = "https://uk.pinterest.com/serenebathrooms/";
$pinterestUrl3 = "https://uk.pinterest.com/jenstanbrook/";
$pinterestUrl4 = "https://uk.pinterest.com/homebaseuk/";
$pinterestUrl5 = "https://uk.pinterest.com/thedoifter/";
$pinterestUrl6 = "https://uk.pinterest.com/coolshitibuy/";
$html1 = file_get_html($pinterestUrl1);
$html2 = file_get_html($pinterestUrl2);
$html3 = file_get_html($pinterestUrl3);
$html4 = file_get_html($pinterestUrl4);
$html5 = file_get_html($pinterestUrl5);
$html6 = file_get_html($pinterestUrl6);
echo $pinterestUrl1 . " - "; if (is_object($html1)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
echo $pinterestUrl2 . " - "; if (is_object($html2)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
echo $pinterestUrl3 . " - "; if (is_object($html3)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
echo $pinterestUrl4 . " - "; if (is_object($html4)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
echo $pinterestUrl5 . " - "; if (is_object($html5)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
echo $pinterestUrl6 . " - "; if (is_object($html6)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
Result:
https://uk.pinterest.com/sfashionality/ - Returns object okay
https://uk.pinterest.com/serenebathrooms/ - Returns object okay
https://uk.pinterest.com/jenstanbrook - Failed
https://uk.pinterest.com/homebaseuk/ - Failed
https://uk.pinterest.com/thedoifter/ - Returns object okay
https://uk.pinterest.com/coolshitibuy/ - Returns object okay
I can't see any reasons why some of these return objects and others don't... and because it's blank I don't even know where to start debugging this kind of thing.
Any ideas at all on this one? Thanks
Simple HTML DOM parser has constant MAX_FILE_SIZE with value 600000 and URLs that you are requesting have slightly more HTML.
You can define MAX_FILE_SIZE with some larger value before including lib, this will produce a PHP notice but HTML will be processed. Code I have tested this with:
<?php
define('MAX_FILE_SIZE', 6000000); //Will produce notice, but we need to define it
include_once './simplehtmldom_1_5/simple_html_dom.php';
$urls = array(
'https://uk.pinterest.com/sfashionality/',
'https://uk.pinterest.com/serenebathrooms/',
'https://uk.pinterest.com/jenstanbrook/',
'https://uk.pinterest.com/homebaseuk/',
'https://uk.pinterest.com/thedoifter/',
'https://uk.pinterest.com/coolshitibuy/',
);
foreach ($urls as $url) {
$content = file_get_contents($url);
$html = str_get_html($content);
echo $url . ' - ';
if (is_object($html)) {
echo 'Returns object okay<br/>';
} else {
echo 'Failed<br/>';
};
}

Using PHP to print to HTML5 output tag

I am new to this. If I have some PHP code as in the example below, I can use the echo function to print the result. Echo always prints at the top of the screen. How do I format the tag so that in this case the result "$myPi" is printed to the screen using an HTML5 output tag? I am a newbie so please be kind to me and don't flame my post - I tried to format the code. Thanks QJB.
function taylorSeriesPi($Iteration)
{
$count = 0;
$myPi = 0.0;
for ($count=0; ($count<$Iteration);$count++)
{
if ( ($count%4) == 1)
{
$myPi = $myPi + (1/$count);
}
if ( ($count%4) == 3)
{
$myPi = $myPi - (1/$count);
}
}
$myPi *= 4.0;
echo ("Pi is ". $myPi. " After ".$Iteration. " iterations");
}
You can insert PHP anywhere in your document, and reference functions from any other place within the document or included files.
For example:
<?php
function taylorSeriesPi($Iteration)
{
$count = 0;
$myPi = 0.0;
for ($count=0; ($count<$Iteration);$count++)
{
...
}
$myPi *= 4.0;
// Return the value so we can use this function later.
return $myPi;
}
?>
<html>
<body>
<div id="somediv">
<?php
$iteration = 6/*or whatever*/;
echo "Pi is " . taylorSeriesPi($iteration) . " After " . $iteration . " iterations";
?>
</div>
</body>
</html>
This will put the returned value and associated string within the <div> tag, but you can put it anywhere in your HTML, as the output of the echo will simply be text by the time the markup is seen by your browser.

PHP controlling the output of rand

Is it possible to control the output of rand, for example if I just want rand to give me the output of the variable $roll1 with the value or number of 1 half the time out of the six possibilities when rand is ran or when the browser is refreshed, how does one accomplish that?
My code sucks but I am fighting to learn, I only get one every now and then, but it's not consistent, I want a 1 every time I refresh the page.
So If I refresh the page 6 times I should get a 1 out of the variable $roll1 three times, and the rest of the values for $roll1 should be random.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>loaded dice</title>
</head>
<body>
<h1>loaded dice</h1>
<h3>loaded dice</h3>
<?php
// loaded dice, should roll the number 1 half the time out of a total of 6.
// So if I refreshed my browser six times I should at least see three 1's for roll1.
$roll1 = rand(1, 6);
// Okay is it possible to divide rand by two or somehow set it up
// so that I get the the value 1 half the time?
// I am trying division here on the if clause in the hopes that I can just have
// 1 half the time, but it's not working,maybe some type of switch might work? :-(.
if ($roll1 == 3) {
$roll1 / 3;
}
if ($roll1 == 6) {
$roll1 / 6;
}
if ($roll1 == 1) {
$roll1 / 1;
}
// This parts works fine :-).
// Normal random roll, is okay.
$roll2 = rand(1, 6);
print <<<HERE
<p>Rolls normal roll:</p>
You rolled a $roll2.
<p>Rolls the number 1 half the time:</p>
<p>You rolled a $roll1.</p>
HERE;
// Notice how we used $roll1 and 2, alongside the HERE doc to echo out a given value.
?>
<p>
Please refresh this page in the browser to roll another die.
</p>
</body>
</html>
You could do something like this
if (rand(0,1))
{
$roll = rand(2,6);
}
else
{
$roll = 1;
}
You can't directly make rand() do that, but you can do something like this:
<?PHP
function roll(){
if(rand(0,1)) //this should evaluate true half the time.
return 1;
return rand(2,6); //the other half of the time we want this.
}
So if you want to guarantee that in the last 6 rolls their would always have been at least 3 ones, I think you would have to track the history of the rolls. Here is a way to do that:
<?php
if (array_key_exists('roll_history', $_GET)) {
$rollHistory = unserialize($_GET['roll_history']);
} else {
$rollHistory = array();
}
$oneCount = 0;
foreach($rollHistory as $roll) {
if ($roll == 1) {
$oneCount++;
}
}
if (6 - count($rollHistory) + $oneCount <= 3) {
$roll = 1;
} else {
if (rand(0,1)) {
$roll = rand(2,6);
} else {
$roll = 1;
}
}
$rollHistory[] = $roll;
if (count($rollHistory) > 5) {
array_shift($rollHistory);
}
echo '<p>Weighted Dice Role: ' . $roll . '</p>';
echo '<form action="' . $_SERVER['PHP_SELF'] . '" method="get" >';
echo '<input type="hidden" name="roll_history" value="' . htmlspecialchars(serialize($rollHistory)) . '" />';
echo '<input type="submit" value="Roll Again" name="roll_again" />';
echo '</form>';
Rather than call rand() twice, you can simply do a little extra math.
$roll = $x = rand(1,12)-6 ? $x : 1;
A slightly different solution. It isn't as elegant, but perhaps more conducive to loading the die more finely?
$i = rand(1, 9);
if($i<=3)
{
$num = 1;
}
else $num = $i-2;

php and mysql not showing data, not entering foreach loop

I am having trouble with modifying a php application to have pagination. My error seems to be with my logic, and I am not clear exactly what I am doing incorrectly. I have had before, but am not currently getting errors that mysql_num_rows() not valid result resource
and that invalid arguments were supplied to foreach. I think there is a problem in my logic which is stopping the results from mysql from being returned.
All my "test" echos are output except testing while loop. A page is generated with the name of the query and the word auctions, and first and previous links, but not the next and last links. I would be grateful if a more efficient way of generating links for the rows in my table could be pointed out, instead of making a link per cell. Is it possible to have a continuous link for several items?
<?php
if (isset($_GET["cmd"]))
$cmd = $_GET["cmd"]; else
die("You should have a 'cmd' parameter in your URL");
$query ='';
if (isset($_GET["query"])) {
$query = $_GET["query"];
}
if (isset($_GET["pg"]))
{
$pg = $_GET["pg"];
}
else $pg = 1;
$con = mysql_connect("localhost","user","password");
echo "test connection<p>";
if(!$con) {
die('Connection failed because of' .mysql_error());
}
mysql_query('SET NAMES utf8');
mysql_select_db("database",$con);
if($cmd=="GetRecordSet"){
echo "test in loop<p>";
$table = 'SaleS';
$page_rows = 10;
$max = 'limit ' .($pg - 1) * $page_rows .',' .$page_rows;
$rows = getRowsByProductSearch($query, $table, $max);
echo "test after query<p>";
$numRows = mysql_num_rows($rows);
$last = ceil($rows/$page_rows);
if ($pg < 1) {
$pg = 1;
} elseif ($pg > $last) {
$pg = $last;
}
echo 'html stuff <p>';
foreach ($rows as $row) {
echo "test foreach <p>";
$pk = $row['Product_NO'];
echo '<tr>' . "\n";
echo '<td>'.$row['USERNAME'].'</td>' . "\n";
echo '<td>'.$row['shortDate'].'</td>' . "\n";
echo '<td>'.$row['Product_NAME'].'</td>' . "\n";
echo '</tr>' . "\n";
}
if ($pg == 1) {
} else {
echo " <a href='{$_SERVER['PHP_SELF']}?pg=1'> <<-First</a> ";
echo " ";
$previous = $pg-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pg=$previous'> <-Previous</a> ";
}
echo "---------------------------";
if ($pg == $last) {
} else {
$next = $pg+1;
echo " <a href='{$_SERVER['PHP_SELF']}?pg=$next'>Next -></a> ";
echo " ";
echo " <a href='{$_SERVER['PHP_SELF']}?pg=$last'>Last ->></a> ";
}
echo "</table>\n";
}
echo "</div>";
function getRowsByProductSearch($searchString, $table, $max) {
$searchString = mysql_real_escape_string($searchString);
$result = mysql_query("SELECT Product_NO, USERNAME, ACCESSSTARTS, Product_NAME, date_format(mycolumn, '%d %m %Y') as shortDate FROM {$table} WHERE upper(Product_NAME) LIKE '%" . $searchString . "%'" . $max);
if($result === false) {
echo mysql_error();
}
$rows = array();
while($row = mysql_fetch_assoc($result)) {
echo "test while <p>";
$rows[] = $row;
}
return $rows;
mysql_free_result($result);
}
edit: I have printed out the mysql error of which there was none. However 8 "test whiles" are printed out, from a database with over 100 records. The foreach loop is never entereded, and I am unsure why.
The problem (or at least one of them) is in the code that reads:
$rows = getRowsByProductSearch($query, $table, $max);
$numRows = mysql_num_rows($rows);
The $numRows variable is not a MySQL resultset, it is just a normal array returned by getRowsByProductSearch.
Change the code to read:
$rows = getRowsByProductSearch($query, $table, $max);
$numRows = count($rows);
Then it should at least find some results for you.
Good luck, James
Hi there,
The next problem is with the line that reads:
$last = ceil($rows/$page_rows);
It should be changed to read:
$last = ceil($numRows / $page_rows);
Would recommend adding the following lines to the start of you script at least while debugging:
ini_set('error_reporting', E_ALL | E_STRICT);
ini_set('display_errors', 'On');
As that would have thrown up a fatal error and saved you a whole lot of time.
if (!(isset($pg))) {
$pg = 1;
}
How is $pg going to get set? You don't appear to be reading it from $_GET. If you're relying on register_globals: don't do that! Try to read it from $_GET and parse it to a positive integer, falling back to '1' if that fails.
<a href='{$_SERVER['PHP_SELF']}?pg=$next'>Next -></a>
You appear to be losing the other parameters your page needs, 'query' and 'cmd'.
In general I'm finding it very difficult to read your code, especially the indentation-free use of echo(). Also you have untold HTML/script-injection vulnerabilities every time you "...$template..." or .concatenate a string into HTML without htmlspecialchars()ing it.
PHP is a templating language: use it, don't fight it! For example:
<?php
// Define this to allow us to output HTML-escaped strings painlessly
//
function h($s) {
echo(htmlspecialchars($s), ENT_QUOTES);
}
// Get path to self with parameters other than page number
//
$myurl= $_SERVER['PHP_SELF'].'?cmd='.urlencode($cmd).'&query='.urlencode($query);
?>
<div id="tableheader" class="tableheader">
<h1><?php h($query) ?> Sales</h1>
</div>
<div id="tablecontent" class="tablecontent">
<table border="0" width="100%"> <!-- width, border, cell width maybe better done in CSS -->
<tr>
<td width="15%">Seller ID</td>
<td width="10%">Start Date</td>
<td width="75%">Description</td>
</tr>
<?php foreach ($rows as $row) { ?>
<tr id="row-<?php h($row['Product_NO']) ?>" onclick="updateByPk('Layer2', this.id.split('-')[1]);">
<td><?php h($row['USERNAME']); ?></td>
<td><?php h($row['shortDate']); ?></td>
<td><?php h($row['Product_NAME']); ?></td>
</tr>
<?php } ?>
</table>
</div>
<div class="pagercontrols">
<?php if ($pg>1) ?>
<<- First
<?php } ?>
<?php if ($pg>2) ?>
<-- Previous
<?php } ?>
<?php if ($pg<$last-1) ?>
Next -->
<?php } ?>
<?php if ($pg<$last) ?>
Last ->>
<?php } ?>
</div>
Is it possible to have a continuous link for several items?
Across cells, no. But you're not really using a link anyway - those '#' anchors don't go anywhere. The example above puts the onclick on the table row instead. What exactly is more appropriate for accessibility depends on what exactly your application is trying to do.
(Above also assumes that the PK is actually numeric, as other characters may not be valid to put in an 'id'. You might also want to consider remove the inline "onclick" and moving the code to a script below - see "unobtrusive scripting".)
This is wrong:
if($cmd=="GetRecordSet")
echo "test in loop\n"; {
It should be:
if($cmd=="GetRecordSet") {
echo "test in loop\n";
In your getRowsByProductSearch function, you return the result of mysql_error if it occurs. In order to debug the code, maybe you can print it instead, so you can easily see what the problem is.

Categories