bɪˈɡɪnə
bɪˈɡɪnə

Reputation: 1085

How to validate data sent through post?

I have ajax code that sends postid and comment to another page.

ajax.php

$.ajax({
            type: "POST",
            url: "addcomment.php",
            data: {comment : comment,postid : postid},

I receive data on other page as:

 if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postid=$_POST['postid'];
    $comment=$_POST['comment'];

Here what improvements I can make to validate the second code. I mean code should proceed only if postid and comment has been posted.

Upvotes: 0

Views: 37

Answers (3)

Massimiliano Fedel
Massimiliano Fedel

Reputation: 120

I would suggest you to create a general purpose Validator class, which will be configured differently according to the form you're going to validate (easily done with a configuration array or file). This way you'll have to do the work only once and you'll be able to re-use it across your project, also making your code cleaner and easy to maintain.

Upvotes: 1

Mikey
Mikey

Reputation: 2704

Well there's a few things you can do, first of all you want to ensure that both of the variables exist, which you can do with an isset()

For code like this I tend to favour early returns over nested ifs, so you could do something like:

if (!isset($_POST['postid']) || !isset($_POST['comment'])) {
    $error = 'Values for postid and comment were not set.';
    return $error;
}

Once you have checked that both variables are set, you could begin to validate whether the variables are the right type and size.

You could potentially replace isset() with empty() so:

if (empty($_POST['postid'] || empty($_POST['comment']) {
    $error = 'Values are not set.';
    return $error;
}

For example I presume postid is a numeric so...

if (!is_numeric($_POST['postid'])) {
    $error = 'Value for postid must be numeric.';
    return $error;
}

You could also do a check that it is above 0: if (!$_POST['postid'] > 0) {}

Then for comment you could check that the length is greater than 0.

if (!strlen($_POST['comment']) > 0) {
    $error = 'Comment was left blank, ensure it is filled in.';
    return $error;
}

So that's just a few examples to get you started, hope it helps. :)

Upvotes: 1

Phil
Phil

Reputation: 4069

Just check that they are defined...

if (isset($_POST['postid']) && isset($_POST['comment'])) {
     //continue
} else {
    // do not continue
}

Or you can do it before you make the AJAX call. Where you grab the value for the postid and comment elements, just check that they have a value. If not return from function.

Upvotes: 1

Related Questions