<?php

$iwout = shell_exec("sudo iwlist wlan0 scan 2>&1");
$wifiscan = explode("\n",$iwout);

$networks = [];
$cur_ssid = '';

foreach ($wifiscan as $line) {

preg_match('/(?<=ESSID:")[^"]+/', $line, $ssid, PREG_OFFSET_CAPTURE, 0);
  if (isset($ssid[0][0])) {
    $cur_ssid = $ssid[0][0];
  } else {
    preg_match('/(?<= Encryption key:)[^\n]+/', $line, $auth, PREG_OFFSET_CAPTURE, 0);
    if (isset($auth[0][0]) && strpos($cur_ssid,'\x00') === false && $cur_ssid != "") {
      $networks[$cur_ssid] = $auth[0][0];
    }
  }
}

ksort($networks);

echo json_encode($networks);

?>
