Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Effective form processing using php

Tags:

oop

ajax

php

I'm working on some project and I want to process requests from forms in several templates. The question is how is to invoke a proper function in the handling scrip. Although, I've been coding for a while, I still cant come up with anything better then using a variable in a hidden field:

if ($_POST['somehiddenfield'] == 1) {
   some_function_1();//doesnt matter if its a function or a method
}

if ($_POST['somehiddenfield'] == 2) {
   $mainclass->somemethod();
}
//goes on indefinitely

Also I want to keep everything in a single handler file, where my main class is invoked. So is there a more effective way than using if ... else?

like image 490
RWS Avatar asked Feb 16 '26 21:02

RWS


1 Answers

I'd do the following:

still have a hidden field, but let it contain something like the form name

<input type="hidden" name="formName" value="post">

Then you can do something like that in the consuming php script:

<?php
// whatever class you use... this is just a simple dummy
class FormsProcessor {
      public function post($params) {
          echo "processing post form";
      }
}

$formName = "post";  // would be $formName = filter_input(INPUT_POST, $_POST['formName'],FILTER_SANITIZE_STRING,FILTER_FLAG_STRIP_HIGH);
// BUT BE SURE TO SANITIZE THE INPUT!!!

$params = [];  // dummy
$formsProcessor = new FormsProcessor();
                 // here's the trick.
$formsProcessor->{$formName}($params);
// to be even safer you could check first if this method_exists() 
// and/or if it's in a list of allowed methods.

Be aware that there mustn't be any other methods in this class that the user shouldn't invoke. You could go around that by really compose the method name of two parts:

$methodName = $formName."Processor";
//....
$formsProcessor->{$methodName}();`
like image 61
Jeff Avatar answered Feb 19 '26 11:02

Jeff