Jump to content

Increment of variable won't work


realWasabi
Go to solution Solved by PaulRyan,

Recommended Posts

Hi.

 

I have a script, where I want it to refresh a page if it meets certain requirements. It have a 'increment'-function so it stops after 10 refreshes or when it meets a certain requirement whichever comes first.

 

I can get it to refresh just fine, but the increment won't work. It just stays on '1' tries.

 

And yes, I use globals - and there's probably other very bad things in there, but I'm a beginner, please don't flame me for that. I'll make something that works, and then can I start to learn to beautify it ;)

 

Besides that - what am I doing wrong?

 

This is the part of my code that refreshes (boiled down to only relevant code):

$maxtries = "10";
$timeout    = "2";
$ip = $_GET["ip"];
$pageurl = pageurl();



function pageurl( ) {
$pageurl = "HTTP";
if ( $_SERVER[ "HTTPS" ] == "on" ) {
$pageurl .= "S";
}
$pageurl .= "://";
if ( $_SERVER[ "SERVER_PORT" ] != "80" ) {
$pageurl .= $_SERVER[ "SERVER_NAME" ] . ":" . $_SERVER[ "SERVER_PORT" ] . $_SERVER[ "REQUEST_URI" ];
} else {
 $pageurl .= $_SERVER[ "SERVER_NAME" ] . $_SERVER[ "REQUEST_URI" ];
}
$urlarts = explode( "?", $pageurl );
$pageurl = $urlarts[ "0" ];
return $pageurl;
}


function htmlheader( ) {
global $tries, $maxtries, $pageurl, $timeout;
if ($tries < $maxtries - 1 ) {
$tries = $tries + 1;
}
$content = "<META HTTP-EQUIV=\"refresh\" CONTENT=\"$timeout;url=$pageurl?ip=10.0.0.14?&tries=$tries\">\n";
return $content;
}

...
else if ($stdout == 0) {
echo '<p style="color:red;">link down</p>';
echo htmlheader();

And this is the whole script:

 

<?php
$descriptorspec = array(
0 => array("pipe", "r"),    // stdin is a pipe that the child will read from
1 => array("pipe", "w"),    // stdout is a pipe that the child will write to
2 => array("pipe", "w")     // stderr is a pipe that the child will write to
);
$maxtries = "10";
$timeout    = "2";
$ip = $_GET["ip"];
$pageurl = pageurl();


function pageurl( ) {
$pageurl = "HTTP";
if ( $_SERVER[ "HTTPS" ] == "on" ) {
$pageurl .= "S";
}
$pageurl .= "://";
if ( $_SERVER[ "SERVER_PORT" ] != "80" ) {
$pageurl .= $_SERVER[ "SERVER_NAME" ] . ":" . $_SERVER[ "SERVER_PORT" ] . $_SERVER[ "REQUEST_URI" ];
} else {
 $pageurl .= $_SERVER[ "SERVER_NAME" ] . $_SERVER[ "REQUEST_URI" ];
}
$urlarts = explode( "?", $pageurl );
$pageurl = $urlarts[ "0" ];
return $pageurl;
}


function htmlheader( ) {
global $tries, $maxtries, $pageurl, $timeout;
if ($tries < $maxtries - 1 ) {
$tries = $tries + 1;
}
$content = "<META HTTP-EQUIV=\"refresh\" CONTENT=\"$timeout;url=$pageurl?ip=10.0.0.14?&tries=$tries\">\n";
return $content;
}


if ($ip == NULL) { 
echo "error";
}
else {
$cmd = "/share/MD0_DATA/scripts/./webping $ip";
$process = proc_open($cmd, $descriptorspec, $pipes);
if (is_resource($process)) {
    $stdin = stream_get_contents($pipes[0]);
    $stdout = stream_get_contents($pipes[1]);
    $stderr = stream_get_contents($pipes[2]);
    fclose($pipes[0]);  fclose($pipes[1]);  fclose($pipes[2]);
    // It is important that you close any pipes before calling proc_close in order to avoid a deadlock
    $return_value = proc_close($process);   
}
if ($stdout == 2) {
echo '<p style="color:green;">link up</p>';
}
else if ($stdout == 1) {
echo '<p style="color:yellow;">link up (warning)</p>';
}
else if ($stdout == 0) {
echo '<p style="color:red;">link down</p>';
echo htmlheader();
}
else {
echo 'error (no IP specified?)';
}
}
?>

 

 

 

 

Link to comment
Share on other sites

<?php
$descriptorspec = array(
0 => array("pipe", "r"),    // stdin is a pipe that the child will read from
1 => array("pipe", "w"),    // stdout is a pipe that the child will write to
2 => array("pipe", "w")     // stderr is a pipe that the child will write to
);
$maxtries = 10;
$timeout = 2;
$ip = $_GET["ip"];
$pageurl = pageurl();
$tries = 1;


function pageurl( ) {
$pageurl = "HTTP";
if ( $_SERVER[ "HTTPS" ] == "on" ) {
$pageurl .= "S";
}
$pageurl .= "://";
if ( $_SERVER[ "SERVER_PORT" ] != "80" ) {
$pageurl .= $_SERVER[ "SERVER_NAME" ] . ":" . $_SERVER[ "SERVER_PORT" ] . $_SERVER[ "REQUEST_URI" ];
} else {
 $pageurl .= $_SERVER[ "SERVER_NAME" ] . $_SERVER[ "REQUEST_URI" ];
}
$urlarts = explode( "?", $pageurl );
$pageurl = $urlarts[ "0" ];
return $pageurl;
}


function htmlheader( ) {
global $tries, $maxtries, $pageurl, $timeout;
if ($tries < $maxtries - 1 ) {
$tries = $tries + 1;
}
$content = "<META HTTP-EQUIV=\"refresh\" CONTENT=\"$timeout;url=$pageurl?ip=10.0.0.14?&tries=$tries\">\n";
return $content;
}


if ($ip == NULL) { 
echo "error";
}
else {
$cmd = "/share/MD0_DATA/scripts/./webping $ip";
$process = proc_open($cmd, $descriptorspec, $pipes);
if (is_resource($process)) {
    $stdin = stream_get_contents($pipes[0]);
    $stdout = stream_get_contents($pipes[1]);
    $stderr = stream_get_contents($pipes[2]);
    fclose($pipes[0]);  fclose($pipes[1]);  fclose($pipes[2]);
    // It is important that you close any pipes before calling proc_close in order to avoid a deadlock
    $return_value = proc_close($process);   
}
if ($stdout == 2) {
echo '<p style="color:green;">link up</p>';
}
else if ($stdout == 1) {
echo '<p style="color:yellow;">link up (warning)</p>';
}
else if ($stdout == 0) {
echo '<p style="color:red;">link down</p>';
echo htmlheader();
}
else {
echo 'error (no IP specified?)';
}
}
?>

I tried "if ($tries < 10 - 1 ) {" but that didn't work. I also tried to change the other "numbers" to "real" numbers like with the $tries variable.

Link to comment
Share on other sites

Incrementing the tries variable does no good, because every time the script is run (each page load) all variables are re-initialized. Values are not carried over from page to page (so $tries always starts at 1).

 

In order for a variable to be maintained from page to page, you need to store it in either a session or a cookie.

Link to comment
Share on other sites

Incrementing the tries variable does no good, because every time the script is run (each page load) all variables are re-initialized. Values are not carried over from page to page (so $tries always starts at 1).

 

In order for a variable to be maintained from page to page, you need to store it in either a session or a cookie.

 

They don't have to be carried over as the URL changes on every update and it just adds 1 to the current 'tries'. This is another, similar script which makes it work without the use of session/cookie:

 

 

<?php
$device     = "roadrunner";
// IP address of device, example "x.x.x.x".
$deviceip   = "10.0.0.14";
// TCP Port on device to check, example "3389" = RDP, "80" = WebServer.
$deviceport = "3389";
// MAC address of NIC1 on device, example "00:00:00:00:00:00" or "00-00-00-00-00-00".
$devicemac1 = "00-11-22-33-44-55";
// MAC address of NIC2 on device, example "00:00:00:00:00:00" or "00-00-00-00-00-00". - Optional set to "" if NIC2 not required.
$devicemac2 = "";
// Number of times to attempt to connect to port on device after magic packet sent, example "10"
$maxtries   = "10";
// Broadcast address of network, example ""x.x.x.x". ("255.255.255.255" works in most cases.)
$broadcast  = "255.255.255.255";
// ICMP port number, default "7".
$udport     = "7";
// Timeout value for re-tries (in seconds), default "10".
$timeout    = "2";
//
// $frame - used to determine which content to display when executed.
$frame      = "1";
// $tries - used to determine number of attempts at checking port beetween reloads, compared with maxtries.
$tries      = $_GET[ "tries" ];
// $pageurl - obtain URL used to access file, used when creating frameset & setting reloads.
$pageurl    = pageurl();
// Process variables used in frame2, increments tries & sets status to Success(1) or Failed(2)
if ( $frame == 1 ) {
               processurl();
}
// ###### Functions ######
//
// function pageurl( ) - Returns URL of page via PHP variables.
function pageurl( )
{
               $pageurl = "HTTP";
               if ( $_SERVER[ "HTTPS" ] == "on" ) {
                               $pageurl .= "S";
               }
               $pageurl .= "://";
               if ( $_SERVER[ "SERVER_PORT" ] != "80" ) {
                               $pageurl .= $_SERVER[ "SERVER_NAME" ] . ":" . $_SERVER[ "SERVER_PORT" ] . $_SERVER[ "REQUEST_URI" ];
               } else {
                               $pageurl .= $_SERVER[ "SERVER_NAME" ] . $_SERVER[ "REQUEST_URI" ];
               }
               $urlarts = explode( "?", $pageurl );
               $pageurl = $urlarts[ "0" ];
               return $pageurl;
}


//  function processurl( ) - Processes variables used in frame2, increments tries & sets status to Success(1) or Failed(2)
function processurl( )
{
               global $status, $tries, $maxtries;
               if ( $status == 0 && $tries < $maxtries - 1 ) {
                               $tries = $tries + 1;
               } else {
                               $status = 2;
               }
               if ( portcheck() == 0 ) {
                               $status = 1; 
               }
}
//  function wakeonlan() - Attempts to send WoL packet and returns outcome.
function wakeonlan( $device, $mac )
{
               global $broadcast, $udport;
               $mac            = preg_replace( "/[^A-Za-z0-9]/", ":", $mac );
               $broadcast_byte = explode( ':', $mac );
               $hw_addr        = '';
               for ( $a = 0; $a < 6; $a++ )
                               $hw_addr .= chr( hexdec( $broadcast_byte[ $a ] ) );
               $msg = chr( 255 ) . chr( 255 ) . chr( 255 ) . chr( 255 ) . chr( 255 ) . chr( 255 );
               for ( $a = 1; $a <= 16; $a++ )
                               $msg .= $hw_addr;
               $s = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );
               if ( $s == false ) {
                               $content = "Error creating socket!\n";
               } else {
                               // setting a broadcast option to socket:
                               $opt_ret = socket_set_option( $s, 1, 6, true );
                               if ( $opt_ret < 0 ) {
                                               $content = "setsockopt() failed, error: " . strerror( $opt_ret ) . "\n";
                               }
                               if ( socket_sendto( $s, $msg, strlen( $msg ), 0, $broadcast, $udport ) ) {
                                               $content = "WoL packet sent to mac address " . $mac . "...\n";
                                               socket_close( $s );
                               } else {
                                               $content = "Failed to send WoL packet!";
                               }
               }
               return $content;
}
//  function portcheck( ) - Attempts to connect to TCP port on the device via a Socket, returns $errno.
function portcheck( )
{
               global $deviceip, $deviceport;
               $file = fsockopen( $deviceip, $deviceport, $errno, $errstr, 50 );
               if ( $errno == 0 ) {
                               fclose( $file );
               }
               return $errno;
}
// function htmlheader( ) - Returns HTML Header for TITLE and if Frame2 REFRESH set.
function htmlheader( )
{
               global $device, $frame, $tries, $maxtries, $status, $pageurl, $timeout;
               // global "custom" header settings
               $content = "<TITLE>PHP WoL ($device) - by PRThomasUK </TITLE>\n";
               //generate refresh header for frame2.
               if ( $status == 0 ) {
                                $content .= "<META HTTP-EQUIV=\"refresh\" CONTENT=\"$timeout;url=$pageurl?&tries=$tries\">\n";
               }
               return $content;
}
// function htmlheader( ) - Returns HTML content for mainpage, frame1 & frame2 based on value of $frame.
function htmlcontent( )
{
               global $pageurl, $device, $deviceip, $deviceport, $devicemac1, $devicemac2, $frame, $tries, $maxtries, $status;
               if ( $frame == 1 ) {
                               if ( $status == 0 ) {
                                $content = "<script type=\"text/javascript\">function stopFrameload() { window.stop(); document.execCommand(\"Stop\");}</script>\n";
                                               $content .= "<p>Checking connectivity... ($tries/$maxtries)   &nbsp<a href=\"\" onclick=\"stopFrameLoad(); return false;\">Stop</a></p>\n";
                               } elseif ( $status == 1 ) {
                                               $content .= "<p>SUCCESS</p>\n";
                               } else {
                                               $content .= "<p>FAILED</p>\n"; }
              } else {
                               $content = "<FRAMESET rows=\"10,*\" frameborder=0 border=0>\n";
                               $content .= "<FRAME SRC=\"$pageurl?frame=2\">\n";
                               $content .= "<NOFRAMES>\n";
                               if ( $devicemac2 ) {
                                               $content .= "<BR>\n";
                                               $content .= wakeonlan( $device, $devicemac2 );
                               }
                               $content .= "<BR>\n";
                               $content .= "<BR>\n";
                               $content .= "<FONT COLOR=\"red\">\n";
                               $content .= "<H2>Your browser does not support frames...</H2>\n";
                               $content .= "</FONT>\n";
                               $content .= "<H3>Status of $device will not be monitored!</H3>\n";
                               $content .= "</NOFRAMES>\n";
                               $content .= "</FRAMESET>\n";
              } return $content; 
}
?>


<?php
echo htmlheader(); 
echo htmlcontent(); 
?>
Link to comment
Share on other sites

 

Well $tries is carried, along with $pageurl, in the META refresh tag.

 

$tries needs to be something like:

$tries = isset($_GET['tries']) ? (int)$_GET['tries'] : 1 ;

Instead of the "$tries = 1;"? Or where do you mean? Because I'm a little unsure about what that string does?

Link to comment
Share on other sites

  • Solution

The above string is whats called a ternary operator (I believe)
 

It is short hand for an if else statement, it is equivalent to the following:

 

<?PHP
  if(isset($_GET['tries'])) {
    $tries = (int)$_GET['tries'];
  } else {
    $tries = 1;
  }
?>

 

And yes, it replaces $tries = 1;

Link to comment
Share on other sites

Woho, it works!

 

Thanks to all of you, but especially PoulRyan for solving the puzzle.

 

I added "else { break; }" after the header if-statement so it stops refreshing after the maxtries have been reached. Also I lowered the tries-number to 0 so it actually does retry 10 times.

 

Just one thing - instead of specifying the IP directly in the meta line, I added the $ip variable. It works, but adds a "?" for every update. So after 10 updates, the url looks like this: http://domain.com/ping.php?ip=10.0.0.14?????????&tries=9

 

I can't figure out why. Any easy way around this?

 

Current script:

 

<?php
$descriptorspec = array(
0 => array("pipe", "r"),    // stdin is a pipe that the child will read from
1 => array("pipe", "w"),    // stdout is a pipe that the child will write to
2 => array("pipe", "w")     // stderr is a pipe that the child will write to
);
$maxtries = 10;
$timeout = 2;
$ip = $_GET["ip"];
$pageurl = pageurl();
$tries = isset($_GET['tries']) ? (int)$_GET['tries'] : 0 ;


function pageurl( ) {
$pageurl = "HTTP";
if ( $_SERVER[ "HTTPS" ] == "on" ) {
$pageurl .= "S";
}
$pageurl .= "://";
if ( $_SERVER[ "SERVER_PORT" ] != "80" ) {
$pageurl .= $_SERVER[ "SERVER_NAME" ] . ":" . $_SERVER[ "SERVER_PORT" ] . $_SERVER[ "REQUEST_URI" ];
} else {
 $pageurl .= $_SERVER[ "SERVER_NAME" ] . $_SERVER[ "REQUEST_URI" ];
}
$urlarts = explode( "?", $pageurl );
$pageurl = $urlarts[ "0" ];
return $pageurl;
}


function htmlheader( ) {
global $ip, $tries, $maxtries, $pageurl, $timeout;
if ($stdout == 0 && $tries < $maxtries - 1 ) {
$tries = $tries + 1;
}
else {
exit;
}
$content = "<META HTTP-EQUIV=\"refresh\" CONTENT=\"$timeout;url=$pageurl?ip=$ip?&tries=$tries\">\n";
return $content;
}


if ($ip == NULL) { 
echo "error";
}
else {
$cmd = "/share/MD0_DATA/scripts/./webping $ip";
$process = proc_open($cmd, $descriptorspec, $pipes);
if (is_resource($process)) {
    $stdin = stream_get_contents($pipes[0]);
    $stdout = stream_get_contents($pipes[1]);
    $stderr = stream_get_contents($pipes[2]);
    fclose($pipes[0]);  fclose($pipes[1]);  fclose($pipes[2]);
    // It is important that you close any pipes before calling proc_close in order to avoid a deadlock
    $return_value = proc_close($process);   
}
if ($stdout == 2) {
echo '<p style="color:green;">link up</p>';
}
else if ($stdout == 1) {
echo '<p style="color:yellow;">link up (warning)</p>';
}
else if ($stdout == 0) {
echo '<p style="color:red;">link down</p>';
echo htmlheader();
}
else {
echo 'error (no IP specified?)';
}
}
?>
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.