Hello I have a four computers that I would like to ping before using. The pinging is done via a PHP page with the following function.
if (isset($_POST['playgroundcheck'])) {
function ping($PGIP) {
require_once "Net/Ping.php";
$ping = Net_Ping::factory();
if (PEAR::isError($ping))
echo $ping -> getMessage();
else {
/* Number of packets to send */
$ping -> setArgs(array('count' => 2));
$pgData = $ping -> ping($PGIP);
// print_r($pgData);
if ($pgData -> _received > 0) {
return true;
//echo "<h1><font color=\"green\">ON</font></h1>";
} else {
//echo "<h1><font color=\"red\">OFF</font></h1>";
return false;
}
}
}
$IP2sping = array("pc1" => "192.168.1.121", "pc2" => "192.168.1.122", "pc3" => "192.168.1.123", "pc4" => "192.168.1.124");
foreach ($IP2sping as $key => $value) {
if (ping($value) == true) {
echo $key . " alive<br>";
} else {
echo $key . " off<br>";
}
}
}
I created a form to call the function with a submit button. All of this works but my problems is trying to display the output outside the function. For example currently all output is displayed like the following.
pc1 alive
pc2 alive
pc3 alive
pc4 alive
I want to know how the results of pc1, pc2, pc3 and pc4 can be displayed separately outside the function.
Thanks for answers, but I found a solution that works great for what I want to do using variables variables.
By changing $key to $$key pc1 pc2 pc3 and pc4 become variables and then I can use it anywhere I want.
$IP2sping = array("pc1" => "192.168.1.121",
"pc2" => "192.168.1.122",
"pc3" => "192.168.1.123",
"pc4" => "192.168.1.124");
foreach ($IP2sping as $key => $value){
if (ping($value) == true) {
$key." alive<br>";
} else {
$key." off<br>"; }
}
}
In fact, it's shown outside the function. Here is where you show the results.
if (ping($value) == true) {
echo $key." alive<br>";
} else {
echo $key." off<br>";
}
I would do something like that for what you want:
$available = null;
foreach ($IP2sping as $key => $value){
if (ping($value) == true) {
echo $key." alive<br>";
} else {
echo $key." off<br>";
}
}
Or
$available = null;
foreach ($IP2sping as $key => $value)
$available[$key] = ping($value) ? true : false;
Then, you'll be able to use the $available array for whatever you want :)
Does this help?
if (isset($_POST['playgroundcheck'])) {
// Define the function
function ping($PGIP) {
require_once "Net/Ping.php";
$ping = Net_Ping::factory();
if (PEAR::isError($ping)) {
return FALSE;
} else {
/* Number of packets to send */
$ping->setArgs(array('count' => 2));
$pgData = $ping->ping($PGIP);
// print_r($pgData);
return ($pgData->_received > 0);
}
}
// Define array of items to ping
$IP2sping = array("pc1" => array('ip' => "192.168.1.121"),
"pc2" => array('ip' => "192.168.1.122"),
"pc3" => array('ip' => "192.168.1.123"),
"pc4" => array('ip' => "192.168.1.124")
);
// Get the results of whether the machines are alive
foreach ($IP2sping as $key => $value){
$IP2sping[$key]['alive'] = ping($value);
}
/*
Do a load more stuff
*/
foreach ($IP2sping as $name => $data) {
echo "$name ({$data['ip']}) is ".(($data['alive']) ? 'alive' : 'dead')."<br />\n";
}
}
Related
I've faced funny bug when modifying the e-store engine:
// ...
$this->toolbar_title[] = 'Products';
// ...
print_r($this->toolbar_title);
/*
Array (
[0] => Products
)
*/
$this->toolbar_title[] = 'Filtered by: name';
print_r($this->toolbar_title);
/*
Array
(
[0] => Products
[2] => Filtered by: name
)
*/
// ...
wat??? where is the "1" index??
Tried to reproduce this in clean stand-alone php script - nope! the added element has index "1" as expected. but when doing the same within the engine code - new element has index "2".
There are no setters, no "[]" overloading found, even no any access to the $this->toolbar_title elements by index, only pushing via [];
What the magic is this? What and where should I seek to find the reason?
PHP 5.6, PrestaShop 1.6 engine.
Thanks a lot in advance for any clue.
UPD: the exact code fragment from engine
if ($filter = $this->addFiltersToBreadcrumbs()) {
echo'131-';print_r($this->toolbar_title);
$this->toolbar_title[] = $filter;
echo'132-';var_dump($this->toolbar_title);
}
where addFiltersToBreadcrumbs returns the string and make NO any access to toolbar_title
UPD2:
public function addFiltersToBreadcrumbs()
{
if ($this->filter && is_array($this->fields_list)) {
$filters = array();
foreach ($this->fields_list as $field => $t) {
if (isset($t['filter_key'])) {
$field = $t['filter_key'];
}
if (($val = Tools::getValue($this->table.'Filter_'.$field)) || $val = $this->context->cookie->{$this->getCookieFilterPrefix().$this->table.'Filter_'.$field}) {
if (!is_array($val)) {
$filter_value = '';
if (isset($t['type']) && $t['type'] == 'bool') {
$filter_value = ((bool)$val) ? $this->l('yes') : $this->l('no');
} elseif (isset($t['type']) && $t['type'] == 'date' || isset($t['type']) && $t['type'] == 'datetime') {
$date = Tools::unSerialize($val);
if (isset($date[0])) {
$filter_value = $date[0];
if (isset($date[1]) && !empty($date[1])) {
$filter_value .= ' - '.$date[1];
}
}
} elseif (is_string($val)) {
$filter_value = htmlspecialchars($val, ENT_QUOTES, 'UTF-8');
}
if (!empty($filter_value)) {
$filters[] = sprintf($this->l('%s: %s'), $t['title'], $filter_value);
}
} else {
$filter_value = '';
foreach ($val as $v) {
if (is_string($v) && !empty($v)) {
$filter_value .= ' - '.htmlspecialchars($v, ENT_QUOTES, 'UTF-8');
}
}
$filter_value = ltrim($filter_value, ' -');
if (!empty($filter_value)) {
$filters[] = sprintf($this->l('%s: %s'), $t['title'], $filter_value);
}
}
}
}
if (count($filters)) {
return sprintf($this->l('filter by %s'), implode(', ', $filters));
}
}
}
For php, if you unset one index in array, the index will appear discontinuous growth.
$this->toolbar_title = array_values($this->toolbar_title);
will rebuild the index.
I am creating an .ics file for outlook calendar, It is working properly when i pass start_time and end_time of event to it but i'm not able to work on all day event. Should i pass 000000 to time for eg. 20190703T000000.
I am passing date time of event like this :
$eventArray[]=array('description'=>'Event','dtstart' => $eventList->date.'T'.$eventList->start_time,'dtend' => $eventList->date.'T'.$eventList->end_time);
Library for icsevent:
<?php
Class Icsevents {
const DT_FORMAT = 'Ymd\THis'; //define date format here
public $events;
public function __construct($events) {
if(count($events)>0) {
for($p=0;$p<=count($events)-1;$p++) {
foreach($events[$p] as $key => $val) {
$events[$p][$key] = $this->sanitize_val($val, $key);
}
}
}
$this->events=$events;
}
private function sanitize_val($val, $key = false) {
switch($key) {
case 'dtend':
case 'dtstamp':
case 'dtstart':
$val = $this->format_timestamp($val);
break;
default:
$val = $this->escape_string($val);
}
return $val;
}
private function format_timestamp($timestamp) {
$dt = new DateTime($timestamp);
return $dt->format(self::DT_FORMAT);
}
private function escape_string($str) {
return preg_replace('/([,;])/','$1', $str);
}
function prepare() {
$cp=array();
if(count($this->events)>0) {
$cp[]= 'BEGIN:VCALENDAR';
$cp[]= 'VERSION:2.0';
$cp[]= 'PRODID:-//hacksw/handcal//NONSGML v1.0//EN//b3';
$cp[]= 'CALSCALE:GREGORIAN';
for($p=0;$p<=count($this->events)-1;$p++) {
$cp[]='BEGIN:VEVENT';
foreach($this->events[$p] as $key => $val) {
if ( $key === 'url' ) {
$cp[]= 'URL;VALUE=URI:'.$val;
} elseif ( $key === 'alarm' ) {
$cp[] = 'BEGIN:VALARM';
$cp[] = 'TRIGGER:-PT' . $val;
$cp[] = 'ACTION:DISPLAY';
$cp[] = 'END:VALARM';
} elseif ( $key === 'dtstart' || $key === 'dtend' ) {
$cp[]= strtoupper($key).';TZID=Asia/Kolkata:'.$val;
} else {
$cp[]= strtoupper($key).':'.$val;
}
}
$cp[]= 'END:VEVENT';
}
$cp[]='END:VCALENDAR';
}
return implode("\r\n", $cp);
}
}
You want to use the DATE format defined in https://www.rfc-editor.org/rfc/rfc5545#section-3.3.4
You can either choose to provide only a DTSTART:
DTSTART;VALUE=DATE:20190703
or, if the allay event last for a longe period of time, provide both DTSTART and DTEND using that same format:
DTSTART;VALUE=DATE:20190703
DTEND;VALUE=DATE:20190712
See also https://devguide.calconnect.org/Handling-Dates-and-Times/
<?php
class User {
public $id;
public $counter;
public $removed;
}
$dB = json_decode(file_get_contents('dataBase.json'), true);
$dataBase = &$dB['noob'];
$userInDB = null;
$user = array('id' => (int)$_GET['id'], 'counter' => (int)$_GET['counter'], 'removed' => (bool)$_GET['removed']);
foreach ($dataBase as $usr) {
if ($usr['id'] == $user['id']) {
$userInDB = &$usr;
break;
}
}
if ($userInDB) {
$userInDB['counter'] = $userInDB['counter'] + $user['counter'];
$userInDB['removed'] = $user['removed'];
print_r($userInDB);
} else {
$dataBase[] = $user;
print_r($dataBase);
}
if(isset($_GET['id'])) {
$json = json_encode($user);
$updateddB = json_encode($dB);
file_put_contents('dataBase.json', $updateddB);
}
?>
Everything works except the part where I attempt to edit a value within an array. $userInDB is changed, but the section that it refers to within $dB isn't, even though I'm pretty sure I referred to it. Someone please help, I've had my head in knots.
You have the following loop:
foreach ($dataBase as $usr) {
if ($usr['id'] == $user['id']) {
$userInDB = &$usr;
break;
}
}
The $userInDB is a reference to $usr, however $usr was just created by the foreach loop, and is is not referenced to the original array it is looping over. So say, for example, you have this very simple case:
foreach ($foo as $var) {
$var++;
}
This does NOT affect $foo at all.
What you need to do is reference the $dataBase variable directly:
foreach ($dataBase as $key => $usr) {
if ($usr['id'] == $user['id']) {
$userInDB = &$dataBase[$key];
break;
}
}
How do I write this code without a foreach loop? I want to fetch the data from the database, but the key and value are stored in the database.
<?php
$options = get_payment_mode_options();
foreach ($options as $key => $value)
{
echo isset($form_data["personal_info"]) && $form_data["personal_info"]->payment_mode == $key ? $value : "";
}
?>
get_payment_mode_options() is function in helper,
function get_payment_mode_options()
{
return array(
"o" => "Online Payment",
"c" => "Cheque Payment"
);
}
Check this,
$options = get_payment_mode_options();
$paymentmode = isset($form_data["personal_info"]) ? $form_data["personal_info"]->payment_mode : '';
echo $options[$paymentmode];
helper function
function get_payment_mode_options()
{
return array(
"o" => "Online Payment",
"c" => "Cheque Payment"
);
}
<?php
function get_payment_mode_options()
{
return array(
"o" => "Online Payment",
"c" => "Cheque Payment"
);
}
// make a new function
function get_your_result($your_key)
{
if (!$your_key) {
return "";
}
$options = get_payment_mode_options();
if(!array_key_exists($your_key,$options)){
return "";
}
return $options[$your_key];
}
// dummy for test
$form_data["personal_info"] = new stdClass();
$form_data["personal_info"]->payment_mode = "o";
$k = $form_data["personal_info"]->payment_mode;
// ~dummy for test
// echo result
echo "----".PHP_EOL;
echo get_your_result($k).PHP_EOL;
echo "----".PHP_EOL;
I'm getting these two php warnings
PHP Warning: Illegal string offset 'subpages'
and
PHP Warning: Invalid argument supplied for foreach() in
The line of code is
foreach ($value ['subpages'] as $subfilename => $subpageTitle) {
and here is the full php so you can see what's going on
Array
// Menu Items
$li_1 = 'Temp Jobs';
$li_2 = 'Domestic Jobs';
$li_3 = 'HR';
$li_4 = 'Job Resume Tips';
$pages = array(
// Temp Jobs
'temp or temporary or seasonal or holiday or part-time or pt' => $li_1,
// Domestic Jobs (with submenu)
$li_2 => array('pageTitle' => $li_2, 'subpages' => array(
'Baby-Sitter or Babysitter' => 'Babysitter',
'Nanny' => 'Nanny',
'Room-Attendant' => 'Room Attendant',
'Butler or Houseman' => 'Butler',
'Chauffeur or Chauffeuse' => 'Chauffeur',
'Maid' => 'Maid',
'Housekeeper or House-Keeper' => 'Housekeeper',
'Estate-Manager' => 'Estate Manager',
'Property-Manager' => 'Property Manager',
'House-Manager' => 'House Manager',
'Tutor' => 'Tutor',
'Caregiver or Nursing-Assistant or CNA' => 'Caregiver')),
// HR
$li_3.' or Human-Resource or Human-Resources' => $li_3,
// Job Resume Tips
'job-resume-tips' => $li_4
);
foreach ($pages as $filename => $value) {
$lis = "";
$hasCurrent = false;
if (is_array ($value)) {
$href = '#menu';
$pageTitle = $value ['pageTitle'];
} elseif (str_replace("-"," ", $filename) == strtolower($value)) {
$href = $dir_structure.$filename.'/';
$pageTitle = $value;
} else {
$href = $dir_structure.'jobs/?position='.urlencode($filename);
$pageTitle = $value;
}
if ($value != '') {
foreach ($value ['subpages'] as $subfilename => $subpageTitle) {
$lis .= '
<li'.(($position == $subfilename) ? ' class="current"' : '').'>'.$subpageTitle.'</li>';
if ($position == $subfilename) {
$hasCurrent = true;
}
} // foreach sub_menus
echo '
<li'.($hasCurrent || $value == $currentPage || $position == $filename ? ' class="current"' : '').'>
'.$pageTitle.'';
if($lis != '') {
echo '
<ul class="subMenu">';
echo $lis;
echo '
</ul>';
} // if lis
} // if sub_menus
echo '
</li>';
} // foreach pages
I already read the other questions on here and know if I replace if ($value != '') { with if (is_array ($value)) { will get rid of the error, but then the navigation menu only shows the tabs that have sub menus. How can I get rid of this php warning and at the same time make sure all of my navigation menu tabs show up? Can't figure it out.
Not all of my top navigation tabs have drop downs. In the example above, only the top tab Domestic Jobs has the drop downs submenu.
In the first iteration of the loop you are trying get the subpages index of a string.
You should also do a is_array check before the loop. So this could work.
if isset($value['subpages']) && (is_array($value['subpages'])) {
foreach ($value ['subpages'] as $subfilename => $subpageTitle) {
This seems to achieve the desired effect;
if(is_array($value)) {
foreach ($value ['subpages'] as $subfilename => $subpageTitle) {
.....
} // if lis
} // if sub_menus
else {
echo '<li class="current">'.$pageTitle.'';
}
if (isset($value['subpages']) && is_array($value['subpages'])) {
foreach ($value['subpages'] as $subfilename => $subpageTitle)
}