lxdware / lxd-dashboard

This LXD dashboard is a web-based user interface (GUI) for managing containers and virtual machines through LXD
https://lxdware.com
GNU Affero General Public License v3.0
317 stars 37 forks source link

Central base.php or config.php #3

Closed kamzar1 closed 3 years ago

kamzar1 commented 3 years ago

The repeating code at start of every php file replace through: require_once('../admin/base.php'); base.php: $cert = "/var/lxdware/data/lxd/client.crt"; $key = "/var/lxdware/data/lxd/client.key";

//Instantiate the GET variables if (isset($_GET['remote'])) $remote = filter_var(urldecode($_GET['remote']), FILTER_SANITIZE_STRING); if (isset($_GET['project'])) $project = filter_var(urldecode($_GET['project']), FILTER_SANITIZE_STRING); if (isset($_GET['instance'])) $instance = filter_var(urldecode($_GET['instance']), FILTER_SANITIZE_STRING);

//Determine host info from database $db = new SQLite3('/var/lxdware/data/sqlite/lxdware.sqlite'); $db_statement = $db->prepare('SELECT * FROM lxd_hosts WHERE id = :id LIMIT 1;'); $db_statement->bindValue(':id', $remote); $db_results = $db_statement->execute(); return $db_results ... or wrap the above as function. can add another repeating tasks as function in base.php as well.

Indeed dont need to put everything inside if (!empty($_SERVER['PHP_AUTH_USER'])) { Can have that in base and if not matched, just redirect to login or ../index.html

kamzar1 commented 3 years ago

in base.php could for example integrate reusable functions like:

  function convert_size($num, int $precision = 2){
                try
                {
                        $num = 0 + str_replace(',', '', $num);
                }
                catch (ErrorException $ee)
                {
                        return false;
                }

      if ($num >= 1000000000000){
        $num  = round($num / 1099511627776, $precision);
        $unit = "TB";
      } elseif ($num >= 1000000000){
        $num  = round($num / 1073741824, $precision);
        $unit = "GB";
      } elseif ($num >= 1000000){
        $num  = round($num / 1048576, $precision);
        $unit = "MB";
      } elseif ($num >= 1000){
        $num  = round($num / 1024, $precision);
        $unit = "KB";
      } else {
        $unit = "B";
      }
        echo number_format($num,2) . ' ' . $unit;
      //return number_format($num,2) . ' ' . $unit;
      }

by elseif and starting at largest, you dont need to define a lot of if only and having between condition >x && <y ... also 1000, 1000000 works nicer than 1024, 1048576 ... because it jumps earlier to next level like 0.95 KB and 0.98 MB

matthewalanpenning commented 3 years ago

@kamzar1 I think this is a great idea. I am planning to start soon to reduce repeated code in PHP, JavaScript, and Bootstrap.

matthewalanpenning commented 3 years ago

I am going to close this as it is a suggestion rather than a bug.