Jump to content

Getting The Key Of An Array


.Stealth

Recommended Posts

Having a bit of trouble, I'm making a class for a simple server testing script i found but i can't get my array key to echo out properly.

First, the code:

 

The class:

 

<?php
class ServerStatus{
function servercheck($server,$port){
	//Check that the port value is not empty
	if(empty($port)){
		$port=80;
	}
	//Check that the server value is not empty
	if(empty($server)){
		$server='localhost';
	}
	//Connection
	$fp=@fsockopen($server, $port, $errno, $errstr, 1);
		//Check if connection is present
		if($fp){
			//Return Alive
			return 1;
		} else{
			//Return Dead
			return 0;
		}
	//Close Connection
	fclose($fp);
}

function doChecks(){
	$serviceStatus = array();
	$services = array(
		'HTTP (Port 80)' => array('localhost' => 80),
		'HTTPS (Port 443)' => array('localhost' => 443),
		'FTP (Port 21)' => array('localhost' => 21),
		'MySQL (Port 3306)' => array('localhost' => 3306),
		'SMTP (Port 25)' => array('localhost' =>  25),
		'POP3 (Port 110)' => array('localhost' =>  110),
		'OFFLINE TEST' => array('http://www.nonexistent.com' => 80)
	);
	foreach($services as $name => $server){
		foreach($server as $host => $port){
			$currentService = key($services);
			if($this->servercheck($host,$port)){
				$serviceStatus[] = array($currentService => 'online');
			}else{
				$serviceStatus[] = array($currentService => 'offline');
			}
		}
	}
	return $serviceStatus;
}

function getServiceStatus(){
	$serviceStatus = $this->doChecks();
	foreach($serviceStatus as $statusArray){
		foreach($statusArray as $service => $status){
			echo $service . ' - ' . $status . '<br />';
		}
	}
}
}
?>

 

 

How it's called:

 

	
        $ServerStatus = new ServerStatus;

$ServerStatus->getServiceStatus();

 

 

Now, the script does it's job apart from echoing out the names of the sites being tested, this is what happens:

 

HTTPS (Port 443) - online

HTTPS (Port 443) - online

HTTPS (Port 443) - online

HTTPS (Port 443) - online

HTTPS (Port 443) - online

HTTPS (Port 443) - online

HTTPS (Port 443) - offline

 

 

And it should be:

 

 

 

HTTP (Port 80) - online

HTTPS (Port 443) - online

FTP (Port 21) - online

MySQL (Port 3306) - online

SMTP (Port 25) - online

POP3 (Port 110) - online

OFFLINE TEST - offline

 

I'm guessing I've got the key() function put in place wrong?

 

Any help please? Thanks.

Link to comment
https://forums.phpfreaks.com/topic/201030-getting-the-key-of-an-array/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.