Are these PHP methods useful?

Hello smart people!

I'm new to PHP and have put together a few helpful methods and created a standard DB connection for a MySQL database so that I can possibly use it for other projects.

Are these methods helpful or can they be improved?

Regards, CodeMaster

Standard methods:

 <?php   function getContentSite($defaultSite) {    if(isset($_GET['site']))    {      include_once($_GET['site'] . ".php");    }    else    {      include_once($defaultSite . ".php");    }  }  function getFormAction()  {    if(isset($_GET["site"]))    {      return htmlspecialchars($_SERVER["PHP_SELF"]) . "?site=" . $_GET["site"];    }    return htmlspecialchars($_SERVER["PHP_SELF"]);  }  function getFormParam($name, $defaultVal = "")  {    if(isset($_POST[$name]))    {      return $_POST[$name];    }    return $defaultVal;  }  function isFormValueChecked($key, $val)  {    return ($key == $val ? "checked"  : "");  }  function isFormValueSelected($key, $val)  {    return ($key == $val ? "selected"  : "");  } ?>

Database connection:

 <?php include_once("dbHelpers.inc.php"); $server = ''; $schema = ''; $user = ''; $password = ''; try{    $con = new PDO('mysql:host='.$server.';dbname='.$schema.';charset=utf8',$user,$password);    $con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); } catch(Exception $e){    printException($e); }

Database queries:

 <?php function makeStatement($query, $array = null){    try{        global $con;        $stmt = $con->prepare($query);        $stmt->execute($array);        return $stmt;    } catch(Exception $e) {        printException($e);    } } function printException($e)  {    echo 'Error '.$e->getCode().$e->getMessage(); } function makeTable($query, $arrV = null) {    try{        $stmt = makeStatement($query, $arrV);        echo '<table class="table">';        $meta = array();        echo '<tr>';        for($i = 0; $i < $stmt -> columnCount(); $i++)        {            $meta[] = $stmt->getColumnMeta($i);            echo '<th>'.$meta[$i]['name'].'</th>';        }        echo '</tr>';         while($row = $stmt->fetch(PDO::FETCH_NUM)){            echo '<tr>';            foreach($row as $r){                echo '<td>'.$r.'</td>';            }            echo '</tr>';        }        echo '</table>';    }    catch(Exception $e){        printException($e);    } }
(2 votes)
Loading...

Similar Posts

Subscribe
Notify of
4 Answers
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
regex9
10 months ago

With the functions that directly process values that come from outside, I would be more restrictive. For getContentSite should be ensured, for example, that only the intended PHP pages can really be called. Collect the best in a special folder where never other PHP files are stored.

Since the function tries to connect the file directly, I would name it a little different.

function includeContentSite($defaultSite) {
  if (!isset($_GET['site'])) {
    require_once($defaultSite . ".php");
    return;
  }

  $site = basename($_GET['site']);
  include_once('path/to/content/sites/folder' . $site . '.php');
}

Even much better, however, would be a routing system that does not link the page name to a file, but a function. First, all requests are redirected to a dispatcher (index.php or the like). There all expected URLs are linked and stored with their associated handlers. If the request URL matches a specific registered entry, the associated handler is executed. A simple implementation becomes in this Article otherwise there are finished (and more mature) implementations in various PHP frameworks (Laravel, Symfony, Yii, etc.).

Similarly, you should be more restrictive in getFormAction trade. See if website contains a valid, intended value before you catch it to an address. In this respect one could also write an auxiliary function:

function getContentSiteName($defaultSite) {
  if (!isset($_GET['site'])) {
    return $defaultSite;
  }

  $site = basename($_GET['site']);
  $sitePath = 'path/to/content/sites/folder' . $site . '.php';

  if (file_exists($sitePath)) {
    return $site;
  }

  return $defaultSite;
}

function getFormAction() {
  $siteName = getContentSiteName('');

  if (!$siteName) {
    return $_SERVER['PHP_SELF'];
  }

  return '?site=' . $siteName;
}

If there is a querystring, this relative address is sufficient. Otherwise, the current file name is output so that the action-Attribute into which the value is written later is not empty.

With regard to functions isValueChecked and isFormValueSelected I can’t say so much as the context in which they will be used later does not reveal to me.

When specifying the connection string, an interpolation would be worth more due to the many string configurations:

$con = new PDO("mysql:host={$server};dbname={$schema};charset=utf8", $user, $password);

And overall, all database operations could be well encapsulated in one class:

class DatabaseHandler {
  public function __construct() {
    /* create PDO connection here ... */
    $this->connection = $connection;
  }

  public function makeStatement($query, $params = null) {
    try {
      $stmt = $this->connection->prepare($query);
      $stmt->execute($params);
      return $stmt;
    }
    catch(Exception $ex) {
      $this->printException($ex);
      return null;
    }
  }

  /* etc. */
}

// usage example:
$dbHandler = new DatabaseHandler();
$result = $dbHandler->makeStatement('select something from somewhere');
$otherResult = $dbHandler->makeStatement('select somethingElse from somewhereElse');

to a global variable $con can therefore be dispensed with. The role of the connectionfield which is known only in the context in which it is also required. If you want to call one of the functions, set an instance of the class and call the respective function.

Make sure to be consistent with value return. If a function returns a value in one of its program branches, it should do so in all other possible program branches.

In the above case (makeStatement) there are two possibilities. Either you give in to failure No (or at least one other falsy value) back or you’re counting on try-catch and instead allows an exception to escalate upwards to then treat it accordingly.

If you select the first option, a caller could be like maketable therefore proceed as follows:

public function makeTable($query, $arrV = null) {
  $stmt = $this->makeStatement($query, $arrV);

  if ($stmt) {
    /* print table ... */
  }
  else {
    /* fallback? */
}

Otherwise, it will remain try-catch– Constructed.

Finally, it would still be good to reconsider the names of some signatories. For example, $ but represent a column and therefore better $column hot. For $arv or $array in turn is unclear from the outside to serve. Your purpose will only become apparent when you look at the specific code of the respective functions.

kernel0verflow
10 months ago

Moin,

So I think the functions are great. They are very short and you know exactly what the individual functions do.

PS. It’s nice to trust newcomers to PHP, because it’s usually rather bad online. But with the latest updates, it’s really great.

Learn a lot of success.

LG.

guteantwort626
10 months ago
Reply to  kernel0verflow

So I find the functions super

As a computer scientist, you should have noticed that you have

include_once($_GET[‘site’) . “.php”);

NIE can do. With this you have installed a great backdoor that can be used to run any PHP file. If there is then another file upload that does not check the file formats, you have an RCE.

codingfreak67
9 months ago

For example, you could link your PHP functions to HTML and view your entries in tables

index.php






    
    
    https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css">
    Document




    

CusSysMgmt

   
           
   

firstPage.php

setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


    $sth = $conn->prepare("SELECT cus_vorname, cus_nachname FROM Customer;");
    $sth->execute();
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}


?>



  

    
    
    fetch(PDO::FETCH_ASSOC)) {
        ?>
        
            
            
        
        
   
VornameNachname

   
   
   
prepare('INSERT INTO Customer (cus_vorname, cus_nachname)         VALUES (?, ?)');     $stmt->execute([$vorname, $nachname]); } ?>
   
   
prepare('DELETE FROM Customer WHERE cus_nachname=?');     $stmt->execute([$nachname]); } ?>

secondPage.php






    
    
    Document




    

Second Page