1

I have this code:

if (strtolower($_POST['skype']) == "yummy") 
   echo "<pre>".file_get_contents("./.htfullapps.txt")."</pre>";
elseif ($_POST['skype'] == '' or 
        $_POST['IGN'] == '' or 
        $_POST['pass'] == '' or 
        !isset($_POST['rules']) or 
        !isset($_POST['group']) or 
        strlen($_POST['pass']) <= 7)
{
    redir( "http://ftb.chipperyman.com/apply/?fail&error=one%20or%20more%20fields%20did%20not%20meet%20the%20minimum%20requirements" ); //Redir is a function defined above and works fine.
    exit;
}

However, I would like to start reporting specific errors. For example, this is how I would do it with if statements:

...
elseif ($_POST['skype'] == '') redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20skype%20is%20invalid%20because%20it%20is%20empty" ); 
elseif ($_POST['IGN'] == '') redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20IGN%20is%20invalid%20because%20it%20is%20empty" ); 
elseif ($_POST['pass'] == '') redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20password%20is%20invalid%20because%20it%20is%20empty" ); 
elseif (strlen($_POST['pass']) <= 7) redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20password%20is%20invalid%20because%20it%20does%20not%20meet%20minimum%20length%20requirements" ); 
...

However that's big, messy and inefficient. What would a solution to this be?

3
  • loop over the fields and check which one is empty Commented Jun 1, 2014 at 23:26
  • This is just a section of my code, some parts are not just about length. Commented Jun 1, 2014 at 23:27
  • 2
    I would recommend not using urlencoding for your error reporting, and instead passing along sessions. Also, why not just make functions to check empty existence of all required fields. Also, the same for length, and then individual password verification requirements. Commented Jun 1, 2014 at 23:33

5 Answers 5

3

You could use associative array like this.

function redir($var){
    echo $var;
}

$skypeErr = array(''=>"http://ftb.chipperyman.com/apply/?fail&error=your%20skype%20is%20invalid%20because%20it%20is%20empty");
$IGNErr = array(''=>'err2');
$passErr = array(''=>'err3',True:'err4');

redir($skypeErr[$_POST['skype']]);
redir($IGNErr[$_POST['IGN']]);
redir($passErr[$_POST['pass']]);
redir($passErr[strlen($_POST['pass'])<=7]);
Sign up to request clarification or add additional context in comments.

1 Comment

Creative, I like it.
2

Create Request class for parsing data from post and get, the class helps you with validation of undefined, empty fields and Report class which helps you with throwing errors.

Here is the very simple Request class:

class Request {
    protected $items = array(
                             'get' => array(),
                             'post' => array()
                       );
    public function __construct(){
        $this->items['post'] = $_POST;
        $this->items['get'] = $_GET;
    }

    public function isPost(){
        return ($_SERVER['REQUEST_METHOD'] == 'POST') ? true : false;
    }

    public function isGet(){
       return ($_SERVER['REQUEST_METHOD'] == 'GET') ? true : false;
    }

    public function getPost($name){
        return (isset($this->items['post'][$name])) ? $this->items['post'][$name] : null; 
    }

    public function get($name){
       return (isset($this->items['get'][$name])) ? $this->items['get'][$name] : null;
    }
}

And Report class:

Class Report {
    protected static $instance;
    private $messages = array();

    private function __construct(){}

    public function getInstance(){
        if(!self::$instance){
            self::$instance = new self();
        }

        return self::$instance;
    }

    public function addReport($message){
        $this->messages[] = $message;
    }

    public function hasReports(){
        return (!empty($this->messages)) ? true : false;
    }
    public function getReports(){
       return $this->messages;
    }

    //this is not so cleaned .... it must be in template but for example
    public function throwReports(){
        if(!empty($this->messages)){
           foreach($this->messages as $message){
               echo $message."<br />";
           }
        }
    }
}

So and how to use is for your problem:

$request = new Request();
$report = Report::getInstance();
if($request->isPost())
{
  if(!$request->getPost("icq")){
    $report->addMessage("you dont enter ICQ");
  }

  if(!$request->getPost("skype")){
    $report->addMessage("you dont enter SKYPE");
  }
  //....etc

  //if we have some reports throw it.
  if($report->hasReports()){
      $reports->throwReports();
  }
}

The report class you can combine with sessions and throw errors after redirect, just update the class to saving reports to session instead of $messages, and after redirect if u will be have messages throw it and clear at the same time.

Comments

1

how about

$field_min_len = array('skype' => 1, 'IGN' => 1, 'pass' => 7);
for ($field_min_len as $f => $l) {
  if (!isset($_POST[$f]) || strlen($_POST[$f]) < $l) {
    redir(...);
    exit;
  }
}

1 Comment

firstly, check syntax
0

Perhaps something like that (reusable, but lengthy):

// validation parameters
$validation = array(
   'skype' => array('check' => 'not_empty', 'error' => 'skype empty'),
   'IGN'   => array('check' => 'not_empty', 'error' => 'IGN empty'),
   'pass'  => array('check' => 'size', 'params' => array(7), 'error' => 'invalid password'),
   'group' => array('check' => 'set', 'error' => 'group unset'),
   'rules' => array('check' => 'set', 'error' => 'group unset')
);

// validation class
class Validator {

  private $params;
  private $check_methods = array('not_empty', 'size', 'set');

  public function __construct($params){
    $this->params = $params;
  }

  private function not_empty($array, $key){
    return $array[$key] == '';
  }

  private function size($array, $key ,$s){
    return strlen($array[$key]) < $s;
  }

  private function set($array, $key){
    return isset($array[$key]);
  }

  private handle_error($err, $msg){
    if ($err) {
       // log, redirect etc.
    }
  }

  public function validate($data){

    foreach($params as $key => $value){
      if (in_array($value['check'], $this->check_methods)){
        $params = $value['params'];
        array_unshift($params, $data, $key);
        $this->handler_error(call_user_func_array(array($this,$value['check']),
                                                  $params),
                             $value['error']);
      }
    }
  }
};


// usage
$validator = new Validator($validation);
$validator->validate($_POST);

Just expand the class with new checks, special log function etc.

Warning: untested code.

Comments

0

This is how I do error reporting now:

$errors = array('IGN' => 'You are missing your IGN', 'skype' => 'You are missing your skype'); //Etc
foreach ($_POST as $currrent) {
    if ($current == '' || $current == null) { 
        //The error should be stored in a session, but the question asked for URL storage
        redir('/apply/?fail='.urlencode($errors[$current])); 
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.