Skip to content
Advertisement

Do I need to verify $_POST before db insertion and what is best way

I would like to ask you if it is neccessary to check $_POST before db insertion even in cases that I know that user must fill these inputs by some data.

And if yes, what is the best way? Because now I use this, but it is quite time consuming to write every one, if I have more inputs.

    if ( isset($_POST['id']) ) {
        $id = $_POST['id'];
    }

    if ( isset($_POST['title']) ) {
        $title = $_POST['title'];
    }

    if ( isset($_POST['text']) ) {
        $text = $_POST['text'];
    }

    if ( isset($_POST['tag']) ) {
        $tag[] = $_POST['tag'];
    }
    ...

    // edit data in db

Thank you

Advertisement

Answer

You can check through a loop whether every field required is provided like this:

$requiredFields = ['id', 'title', 'text', 'tag'];
foreach ($requiredFields as $fieldName) {
    if (!array_key_exists($fieldName, $_POST)) {
        echo "Field {$fieldName} is required";
        break;
    }
}

Then you can safely assign them to variables

$id = $_POST['id'];
$title = $_POST['title'];
$text = $_POST['text'];
$tag = $_POST['tag'];

You can use the extract() function to assign the input to variables dynamically, but I wouldn’t recommend this, because your code will be impolite.

Next, you should validate each field, think about:

  • Is id numeric? Should it be?
  • Is the string length of title above 0?
  • Are the characters in the text field perhaps too long? Should you show an error if this is the case.

After that, if you are inserting the data into the database yourself, read about escaping each parameter to prevent MySQL Injection.

You should always assume that the end user who fills in the form will be an attacker. Don’t leave your database vulnerable.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement