test a connection to a network device using snmp - php

I have this code to retrieve some countervalues of a copymachine.
foreach($sett as $key => $value){
if (intval(str_replace("INTEGER: ","",snmpget($ip, "public", $base.$value["MIB"])))) {
$c = intval(str_replace("INTEGER: ","",snmpget($ip, "public", $base.$value["MIB"])));
$error = false;
}
else {
$c = 0;
$error = true;
}
$counters = array_push_assoc($counters,ucwords($key),array("total" => $c, "code" => $value["code"]));
}
everything works like a charm but the only thing that is the problem is when a machine is down en the code cannot make an SNMPGET, the whole script fails.
First I want to check if the connection to the device is alive and then retrieve the counters with SNMPGET
Is there any solution you guys can offer me?
thx

The snmpget() function returns FALSE if it fails to retrieve the object.
See docs: http://www.php.net/manual/en/function.snmpget.php
You should do a check for this within your code, for example:
try
{
foreach($sett as $key => $value){
$sntpReturn = snmpget($ip, "public", $base.$value["MIB"]);
if ($sntpReturn === false)
{
// Do something to handle failed SNTP request.
throw new Exception("Failed to execute the SNTP request to the machine.");
}
else
{
if (intval(str_replace("INTEGER: ","", $sntpReturn))) {
$c = intval(str_replace("INTEGER: ","",snmpget($ip, "public", $base.$value["MIB"])));
$error = false;
}
else {
$c = 0;
$error = true;
}
$counters = array_push_assoc($counters,ucwords($key),array("total" => $c, "code" => $value["code"]));
}
}
catch (Exception $e)
{
// Handle the exception, maybe kill the script because it failed?
}

Related

For each loop continious but doesn't fill array

Problem
Hey, my array $isActiefErr and $naamErr doesn't fill up after I throw an exception, but the foreach loop does continue to validate the values. I know the foreach loop keeps on looping, because the array which should have all the values is filled, but the error array stops after it encounters its first error.
What I have tried:
I've tried to print the array but it only pushes the first error into my array. It then stops validating. This also shows in my error log. I think the problem would be the try/catch, but I simply cannot confirm this, because of my lack of knowledge regarding try/catches.
Question
How can I get the array to push and display all the errors with a try/catch block surrounding it? Or am I simply missing something and isn't the problem related to the try/catch?
This is my code:
$validateOk = 0;
$setVar = new SetVariable();
$teller = 1;
$save = null;
$validateOk = 0;
$con->beginTransaction();
$weg = TypeQuery::create()->find();
$weg->delete();
try {
foreach ($_POST as $key => $value) {
if (isEven($teller)) {
$validateOk += $setVar->nameval($key)
->onerror($isActiefErr[]) //errors aren't being pushed into this array, besides the first one.
->validator(v::numericVal())
->go();
if ($validateOk == 0) {
$save->setCode(substr($key, 1));
$save->setIsActief($value);
$save->save();
} else {
//ROLLBACK/CATCH
throw new Exception($error);
}
} else {
$validateOk += $setVar->nameval($key)
->onerror($naamErr[])
->validator(v::alpha('/()éá&., '))
->go();
if ($validateOk == 0) {
$save = new Type();
$save->setCode(substr($key, 1));
$save->setNaam($value);
} else {
//ROLLBACK/CATCH
throw new Exception($error);
}
}
$teller += 1;
}
$con->commit();
} catch (Exception $e) {
$error = "Het opslaan is fout gegaan!";
} {
$con->rollback();
}

php include or require contents of a variable, not a file

I'm looking for a way to include or require the content of a variable, instead of a file.
Normally, one can require/include a php function file with either of these:
require_once('my1stphpfunctionfile.php')
include('my2ndphpfunctionfile.php');
Suppose I wanted to do something like this:
$contentOf1stFFile = file_get_contents('/tmp/my1stphpfunctionfile.php');
$contentOf2ndFFile = file_get_contents('/tmp/my2ndphpfunctionfile.php');
require_once($contentOf1stFFile);
require_once($contentOf2ndFFile);
Now, in the above example, I have the actual function files which I am loading into variables. In the real world scenario I'm actually dealing with, the php code in the function files are not stored in files. They're in variables. So I'm looking for a way to treat those variables as include/require treats the function files.
I'm new to php so please forgive these questions if you find them foolish. What I'm attempting to do here does not appear to be possible. What I ended up doing was using eval which I'm told is very dangerous and should be avoided:
eval("?>$contentOf1stFFile");
eval("?>$contentOf2ndFFile");
Content of $contentOf1stFFile:
# class_lookup.php
<?php
class Lookup_whois {
// Domain name which we want to lookup
var $domain;
// TLD for above domain, eg. 'com', 'net', etc...
var $tld;
// Array which contains information needed to parse the whois server response
var $tld_params;
// Sets to error code if something fails
var $error_code;
// Sets user-friendly error message if something goes wrong
var $error_message;
// For internal use mainly - raw response from the whois server
var $whois_raw_output;
function Lookup_whois($domain, $tld, $tld_params) {
$this->domain = $domain;
$this->tld = $tld;
$this->tld_params = $tld_params;
}
function check_domain_spelling() {
if (preg_match("/^([A-Za-z0-9]+(\-?[A-za-z0-9]*)){2,63}$/", $this->domain)) {
return true;
} else {
return false;
}
}
function get_whois_output() {
if (isset($this->tld_params[$this->tld]['parameter'])) {
$query = $this->tld_params[$this->tld]['parameter'].$this->domain.'.'.$this->tld;
} else {
$query = $this->domain.'.'.$this->tld;
}
$server = $this->tld_params[$this->tld]['whois'];
if (!$this->check_domain_spelling()) {
$this->error_message = 'Domain name is not correct, check spelling. Only numbers, letters and hyphens are allowed';
return false;
}
if (!$server) {
$this->error_message = 'Whois server name is empty, please check the config file';
return false;
}
$output = array();
$fp = fsockopen($server, 43, $errno, $errstr, 30);
if(!$fp) {
$this->error_code = $errno;
$this->error_message = $errstr;
fclose($fp);
return false;
} else {
sleep(2);
fputs($fp, $query . "\n");
while(!feof($fp)) {
$output[] = fgets($fp, 128);
}
fclose($fp);
$this->whois_raw_output = $output;
return true;
}
}
function parse_whois_data() {
if (!is_array($this->whois_raw_output) && Count($this->whois_raw_output) < 1) {
$this->error_message = 'No output to parse... Get data first';
return false;
}
$wait_for = 0;
$result = array();
$result['domain'] = $this->domain.'.'.$this->tld;
foreach ($this->whois_raw_output as $line) {
#if (ereg($this->tld_params[$this->tld]['wait_for'], $line)) {
if (preg_match($this->tld_params[$this->tld]['wait_for'],$line)) {
$wait_for = 1;
}
if ($wait_for == 1) {
foreach ($this->tld_params[$this->tld]['info'] as $key => $value) {
$regs = '';
if (ereg($value.'(.*)', $line, $regs)) {
if (key_exists($key, $result)) {
if (!is_array($result[$key])) {
$result[$key] = array($result[$key]);
}
$result[$key][] = trim($regs[1]);
} else {
$result[$key] = trim($regs[1]);
$i = 1;
}
}
}
}
}
return $result;
}
}
?>
Are there any other alternatives?
No there are no other alternatives.
In terms of security there is no difference if you include() a file or eval() the content. It depends on the context. As long as you only run your own code there is nothing "dangerous".

silverstripe, how to use the doPublish()

I am working with SilverStripe, and I am working on making a newspage.
I use the DataObjectAsPage Module( http://www.ssbits.com/tutorials/2012/dataobject-as-pages-the-module/ ), I got it working when I use the admin to publish newsitems.
Now I want to use the DataObjectManager Module instead of the admin module to manage my news items. But this is where the problem exists. Everything works fine in draft mode, I can make a new newsitem and it shows up in draft. But when I want to publish a newsitem, it won't show up in the live or published mode.
I'm using the following tables:
-Dataobjectaspage table,
-Dataobjectaspage_live table,
-NewsArticle table,
-NewsArticle_Live table
The Articles have been inserted while publishing in the Dataobjectaspage table and in the NewsArticle table... But not in the _Live tables...
Seems the doPublish() function hasn't been used while 'Publishing'.
So I'm trying the use the following:
function onAfterWrite() {
parent::onAfterWrite();
DataObjectAsPage::doPublish();
}
But when I use this, it gets an error:
here is this picture
It seems to be in a loop....
I've got the NewsArticle.php file where I use this function:
function onAfterWrite() {
parent::onAfterWrite();
DataObjectAsPage::doPublish();
}
This function calls the DataObjectAsPage.php file and uses this code:
function doPublish() {
if (!$this->canPublish()) return false;
$original = Versioned::get_one_by_stage("DataObjectAsPage", "Live", "\"DataObjectAsPage\".\"ID\" = $this->ID");
if(!$original) $original = new DataObjectAsPage();
// Handle activities undertaken by decorators
$this->invokeWithExtensions('onBeforePublish', $original);
$this->Status = "Published";
//$this->PublishedByID = Member::currentUser()->ID;
$this->write();
$this->publish("Stage", "Live");
// Handle activities undertaken by decorators
$this->invokeWithExtensions('onAfterPublish', $original);
return true;
}
And then it goes to DataObject.php file and uses the write function ():
public function write($showDebug = false, $forceInsert = false, $forceWrite = false, $writeComponents = false) {
$firstWrite = false;
$this->brokenOnWrite = true;
$isNewRecord = false;
if(self::get_validation_enabled()) {
$valid = $this->validate();
if(!$valid->valid()) {
// Used by DODs to clean up after themselves, eg, Versioned
$this->extend('onAfterSkippedWrite');
throw new ValidationException($valid, "Validation error writing a $this->class object: " . $valid->message() . ". Object not written.", E_USER_WARNING);
return false;
}
}
$this->onBeforeWrite();
if($this->brokenOnWrite) {
user_error("$this->class has a broken onBeforeWrite() function. Make sure that you call parent::onBeforeWrite().", E_USER_ERROR);
}
// New record = everything has changed
if(($this->ID && is_numeric($this->ID)) && !$forceInsert) {
$dbCommand = 'update';
// Update the changed array with references to changed obj-fields
foreach($this->record as $k => $v) {
if(is_object($v) && method_exists($v, 'isChanged') && $v->isChanged()) {
$this->changed[$k] = true;
}
}
} else{
$dbCommand = 'insert';
$this->changed = array();
foreach($this->record as $k => $v) {
$this->changed[$k] = 2;
}
$firstWrite = true;
}
// No changes made
if($this->changed) {
foreach($this->getClassAncestry() as $ancestor) {
if(self::has_own_table($ancestor))
$ancestry[] = $ancestor;
}
// Look for some changes to make
if(!$forceInsert) unset($this->changed['ID']);
$hasChanges = false;
foreach($this->changed as $fieldName => $changed) {
if($changed) {
$hasChanges = true;
break;
}
}
if($hasChanges || $forceWrite || !$this->record['ID']) {
// New records have their insert into the base data table done first, so that they can pass the
// generated primary key on to the rest of the manipulation
$baseTable = $ancestry[0];
if((!isset($this->record['ID']) || !$this->record['ID']) && isset($ancestry[0])) {
DB::query("INSERT INTO \"{$baseTable}\" (\"Created\") VALUES (" . DB::getConn()->now() . ")");
$this->record['ID'] = DB::getGeneratedID($baseTable);
$this->changed['ID'] = 2;
$isNewRecord = true;
}
// Divvy up field saving into a number of database manipulations
$manipulation = array();
if(isset($ancestry) && is_array($ancestry)) {
foreach($ancestry as $idx => $class) {
$classSingleton = singleton($class);
foreach($this->record as $fieldName => $fieldValue) {
if(isset($this->changed[$fieldName]) && $this->changed[$fieldName] && $fieldType = $classSingleton->hasOwnTableDatabaseField($fieldName)) {
$fieldObj = $this->dbObject($fieldName);
if(!isset($manipulation[$class])) $manipulation[$class] = array();
// if database column doesn't correlate to a DBField instance...
if(!$fieldObj) {
$fieldObj = DBField::create('Varchar', $this->record[$fieldName], $fieldName);
}
// Both CompositeDBFields and regular fields need to be repopulated
$fieldObj->setValue($this->record[$fieldName], $this->record);
if($class != $baseTable || $fieldName!='ID')
$fieldObj->writeToManipulation($manipulation[$class]);
}
}
// Add the class name to the base object
if($idx == 0) {
$manipulation[$class]['fields']["LastEdited"] = "'".SS_Datetime::now()->Rfc2822()."'";
if($dbCommand == 'insert') {
$manipulation[$class]['fields']["Created"] = "'".SS_Datetime::now()->Rfc2822()."'";
//echo "<li>$this->class - " .get_class($this);
$manipulation[$class]['fields']["ClassName"] = "'$this->class'";
}
}
// In cases where there are no fields, this 'stub' will get picked up on
if(self::has_own_table($class)) {
$manipulation[$class]['command'] = $dbCommand;
$manipulation[$class]['id'] = $this->record['ID'];
} else {
unset($manipulation[$class]);
}
}
}
$this->extend('augmentWrite', $manipulation);
// New records have their insert into the base data table done first, so that they can pass the
// generated ID on to the rest of the manipulation
if(isset($isNewRecord) && $isNewRecord && isset($manipulation[$baseTable])) {
$manipulation[$baseTable]['command'] = 'update';
}
DB::manipulate($manipulation);
if(isset($isNewRecord) && $isNewRecord) {
DataObjectLog::addedObject($this);
} else {
DataObjectLog::changedObject($this);
}
$this->onAfterWrite();
$this->changed = null;
} elseif ( $showDebug ) {
echo "<b>Debug:</b> no changes for DataObject<br />";
// Used by DODs to clean up after themselves, eg, Versioned
$this->extend('onAfterSkippedWrite');
}
// Clears the cache for this object so get_one returns the correct object.
$this->flushCache();
if(!isset($this->record['Created'])) {
$this->record['Created'] = SS_Datetime::now()->Rfc2822();
}
$this->record['LastEdited'] = SS_Datetime::now()->Rfc2822();
} else {
// Used by DODs to clean up after themselves, eg, Versioned
$this->extend('onAfterSkippedWrite');
}
// Write ComponentSets as necessary
if($writeComponents) {
$this->writeComponents(true);
}
return $this->record['ID'];
}
Look at the $this->onAfterWrite();
It probably goes to my own function on NewsArticle.php and there starts the loop! I'm not sure though, so i could need some help!!
Does anyone knows how to use the doPublish() function?
The reason that is happening is that in the DataObjectAsPage::publish() method, it is calling ->write() - line 11 of your 3rd code sample.
So what happens is it calls ->write(), at the end of ->write() your onAfterWrite() method is called, which calls publish(), which calls write() again.
If you remove the onAfterWrite() function that you've added, it should work as expected.
The doPublish() method on DataObjectAsPage will take care of publishing from Stage to Live for you.

Telnet to cisco switch using php

I need to telnet to cisco switch using php and execute show interface status command and get results. I tried some php classes I found on internet but none of them could connect to device. So I tried to write the script myself, but I have the same problem, I cant connect to device.
The host sends me banner message and then new line with username:.
I send my username with \r\n, wait some time and tries to read data, but it looks to me like host is just ignoring my new line characters. This is response I got (explode('\n') on response):
Array
(
[0] => %
[1] => User Access Verification
[2] => Username: timeout expired!
)
Why didn't I get prompt on password? I tried it with sending telnet headers, and without, no change. Can anyone please help me?
Here is my code
<?
$host = "switchName";
$name = "name";
$pass = "pass";
$port = 23;
$timeOut = 15;
$connected = false;
$skipNullLines = true;
$timeout = 125000;
$header1=chr(0xFF).chr(0xFB).chr(0x1F).chr(0xFF).chr(0xFB).chr(0x20).chr(0xFF).chr(0xFB).chr(0x18).chr(0xFF).chr(0xFB).chr(0x27).chr(0xFF).chr(0xFD).chr(0x01).chr(0xFF).chr(0xFB).chr(0x03).chr(0xFF).chr(0xFD).chr(0x03).chr(0xFF).chr(0xFC).chr(0x23).chr(0xFF).chr(0xFC).chr(0x24).chr(0xFF).chr(0xFA).chr(0x1F).chr(0x00).chr(0x50).chr(0x00).chr(0x18).chr(0xFF).chr(0xF0).chr(0xFF).chr(0xFA).chr(0x20).chr(0x00).chr(0x33).chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0x2C).chr(0x33).chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0xFF).chr(0xF0).chr(0xFF).chr(0xFA).chr(0x27).chr(0x00).chr(0xFF).chr(0xF0).chr(0xFF).chr(0xFA).chr(0x18).chr(0x00).chr(0x41).chr(0x4E).chr(0x53).chr(0x49).chr(0xFF).chr(0xF0);
$header2=chr(0xFF).chr(0xFC).chr(0x01).chr(0xFF).chr(0xFC).chr(0x22).chr(0xFF).chr(0xFE).chr(0x05).chr(0xFF).chr(0xFC).chr(0x21);
function read_string()
{
global $fw,$host,$skipNullLines;
$string = "";
while( !feof($fw) )
{
$read = fgets($fw);
$string .= $read;
// Probably prompt, stop reading
if( strpos($read, ':') !== FALSE || strpos($read, '> (enable)') !== FALSE || strpos($read, $host.'#') !== FALSE)
{ break; }
}
$string = explode("\n", $string);
// Get rid of null lines
$ret = array();
for($i = 0; $i<count($string); $i++)
{
if( trim($string[$i]) == '' && $skipNullLines ) continue;
$ret[] = $string[$i];
}
return $ret;
}
function send_string($string, $force=false)
{
GLOBAL $timeout,$fw;
$string = trim($string);
// execute only strings that are preceded by "show" (if not forced)
if(!$force && strpos($string, 'show ') !== 0)
{
return 1;
}
fputs($fw, $string."\r\n");
echo("SEND:".$string."\r\n");
usleep($timeout);
}
$fw = fsockopen($host, $port, $errno, $errorstr, $timeOut);
if($fw == false)
{
echo("Cant connect");
}
else
{
echo("Connected<br>");
$connected = true;
stream_set_timeout($fw, $timeout);
// fputs($fw, $header1);
// usleep($timeout);
// fputs($fw, $header2);
// usleep($timeout);
print_r(read_string());
send_string("test", true);
print_r(read_string());
}
fclose($fw);
?>
UPDATE
If I send username at first, and then I read, I get password prompt. I dont understand it, why cant I firstly read messages from host and then send my response. The way it works to me now (send response and then read for prompt) is no-sense! (and I still got "% Authentication failed." message event with right password/name).
...
$connected = true;
stream_set_timeout($fw, $timeout);
send_string("name", true);
send_string("password", true);
print_r(read_string());
...
Okay, so I dont know what was the problem, but after "few" tests I was able to write this class that works for me. I dont know why other telnet classes dont work altough they do pretty much the same. So if anyone will have similar problem, you can try this:
class TELNET
{
private $host;
private $name;
private $pass;
private $port;
private $connected;
private $connect_timeout;
private $stream_timetout;
private $socket;
public function TELNET()
{
$this->port = 23;
$this->connected = false; // connected?
$this->connect_timeout = 10; // timeout while asking for connection
$this->stream_timeout = 380000; // timeout between I/O operations
}
public function __destruct()
{
if($this->connected) { fclose($this->socket); }
}
// Connects to host
// #$_host - addres (or hostname) of host
// #$_user - name of user to log in as
// $#_pass - password of user
//
// Return: TRUE on success, other way function will return error string got by fsockopen()
public function Connect($_host, $_user, $_pass)
{
// If connected successfully
if( ($this->socket = #fsockopen($_host, $this->port, $errno, $errorstr, $this->connect_timeout)) !== FALSE )
{
$this->host = $_host;
$this->user = $_user;
$this->pass = $_pass;
$this->connected = true;
stream_set_timeout($this->socket, 0, 380000);
stream_set_blocking($this->socket, 1);
return true;
}
// else if coulnt connect
else return $errorstr;
}
// LogIn to host
//
// RETURN: will return true on success, other way returns false
public function LogIn()
{
if(!$this->connected) return false;
// Send name and password
$this->SendString($this->user, true);
$this->SendString($this->pass, true);
// read answer
$data = $this->ReadTo(array('#'));
// did we get the prompt from host?
if( strtolower(trim($data[count($data)-1])) == strtolower($this->host).'#' ) return true;
else return false;
}
// Function will execute command on host and returns output
//
// #$_command - command to be executed, only commands beginning with "show " can be executed, you can change this by adding
// "true" (bool type) as the second argument for function SendString($command) inside this function (3rd line)
//
function GetOutputOf($_command)
{
if(!$this->connected) return false;
$this->SendString($_command);
$output = array();
$work = true;
//
// Read whole output
//
// read_to( array( STRINGS ) ), STRINGS are meant as possible endings of outputs
while( $work && $data = $this->ReadTo( array("--More--","#") ) )
{
// CHeck wheter we actually did read any data
$null_data = true;
foreach($data as $line)
{
if(trim($line) != "") {$null_data = false;break;}
}
if($null_data) { break;}
// if device is paging output, send space to get rest
if( trim($data[count($data)-1]) == '--More--')
{
// delete line with prompt (or "--More--")
unset($data[count($data)-1]);
// if second line is blank, delete it
if( trim($data[1]) == '' ) unset($data[1]);
// If first line contains send command, delete it
if( strpos($data[0], $_command)!==FALSE ) unset($data[0]);
// send space
fputs($this->socket, " ");
}
// ak ma vystup max dva riadky
// alebo sme uz nacitali prompt
// IF we got prompt (line ending with #)
// OR string that we've read has only one line
// THEN we reached end of data and stop reading
if( strpos($data[count($data)-1], '#')!==FALSE /* || (count($data) == 1 && $data[0] == "")*/ )
{
// delete line with prompt
unset($data[count($data)-1]);
// if second line is blank, delete it
if( trim($data[1]) == '' ) unset($data[1]);
// If first line contains send command, delete it
if( strpos($data[0], $_command)!==FALSE ) unset($data[0]);
// stop while cyclus
$work = false;
}
// get rid of empty lines at the end
for($i = count($data)-1; $i>0; $i--)
{
if(trim($data[$i]) == "") unset($data[$i]);
else break;
}
// add new data to $output
foreach($data as $v)
{ $output[] = $v; }
}
// return output
return $output;
}
// Read from host until occurence of any index from $array_of_stops
// #array_of_stops - array that contains strings of texts that may be at the end of output
// RETURNS: output of command as array of lines
function ReadTo($array_of_stops)
{
$ret = array();
$max_empty_lines = 3;
$count_empty_lines = 0;
while( !feof($this->socket) )
{
$read = fgets($this->socket);
$ret[] = $read;
//
// Stop reading after (int)"$max_empty_lines" empty lines
//
if(trim($read) == "")
{
if($count_empty_lines++ > $max_empty_lines) break;
}
else $count_empty_lines = 0;
//
// Does last line of readed data contain any of "Stop" strings ??
$found = false;
foreach($array_of_stops AS $stop)
{
if( strpos($read, $stop) !== FALSE ) { $found = true; break; }
}
// If so, stop reading
if($found) break;
}
return $ret;
}
// Send string to host
// If force is set to false (default), function sends to host only strings that begins with "show "
//
// #$string - command to be executed
// #$force - force command? Execute if not preceeded by "show " ?
// #$newLine - append character of new line at the end of command?
function SendString($string, $force=false, $newLine=true)
{
$t1 = microtime(true);
$string = trim($string);
// execute only strings that are preceded by "show"
// and execute only one command (no new line characters) !
if(!$force && strpos($string, 'show ') !== 0 && count(explode("\n", $string)) == 1)
{
return 1;
}
if($newLine) $string .= "\n";
fputs($this->socket, $string);
$t2 = microtime(true);
}
}
// EXAMPLE
$host = "hostname";
$name = "username";
$pass = "password";
$t = new TELNET();
echo("CONNECT:".$t->Connect($host, $name, $pass)."<br>");
echo("LOGIN:".(int)$t->LogIn());
echo("<br>OUTPUT:<br>");
print_r($t->GetOutputOf("show snmp"));
print_r($t->GetOutputOf("show users"));
print_r($t->GetOutputOf("show interface status"));
PS: my devices prompt is "hostname#", so you may need to edit Login function to make this code work with prompt of your device (so you may need in GetOutputOf() )

trying to save time with PHP if/elseif statements

I have a rather big if statement:
if (!$result_spam)
{
$confrim_spam = "FAILED";
}
else if ($result_spam)
{
$confrim_spam = "PASSED";
}
if (!$result_email_manage)
{
$confrim_email_manage = "FAILED";
}
else if ($result_email_manage)
{
$confrim_email_manage = "PASSED";
}
if (!$result_analyt)
{
$confrim_analytics = "FAILED";
}
else if ($result_analyt)
{
$confrim_analytics = "PASSED";
}
Now I want to do another if statement to check if all have PASSED or if all have FAILED or is some have PASSED and some have FAILED and then echo (do something with) the failed ones.
I know how to check if all have passed or failed:
if ($confirm_spam == "PASSED" AND $confirm_analytics == "PASSED"
but to check if some have passed and some haven't and then find the ones that failed will take too long, right?
I was just wondering, would there be an easier/quicker way to do this?
Since they are all bools anyway:
if($result_spam && $result_email_manage && $result_analyt){
//do all passed
}
elseif($result_spam || $result_email_manage || $result_analyt){
//at least one passed
if(!$result_spam){ echo '$result_spam failed';}
if(!$result_email_manage){ echo '$result_email_manage failed';}
if(!$result_analyt){ echo '$result_analyt failed';}
}
else {
//do all failed
}
You can change validation logic to something like
$passed = array();
$failed = array();
if (!$result_spam)
{
array_push($failed, "confirm_spam");
}
else
{
array_push($passed, "confirm_spam");
}
...
Then you have an easy and clear way to check whether all passed/failed and which tests are failed.
What if you try this way:
$passed = $failed = "";
$all = array("confrim_spam" => $result_spam,
"confrim_email_manage" => $result_email_manage,
"confrim_analytics" => $result_analyt);
foreach($all as $a => $b)
{
if (!$b)
$failed.= $a . ", ";
else
$passed.= $a . ", ";
}
Then if var $passed is empty, none passed else if $failed is not empty, at last one have not passed.. so do you got what passed and what failed and do something with them. And you can store results both in a string or an array whatever you want...

Categories