0

I have this setup: HTML Form with submit button -> Check if the button was pressed in jquery -> then send input via $.post (jquery) to a php page.

How can i tell in the php code if someone actually pressed the button in the HTML form? I want to prevent users from submitting $_POST values to the php page without going through my form.

0

2 Answers 2

1

I would do the following:

  1. Have a hidden post value in the form that generates a random hashed token based on current date/time.
  2. Save this token when form is submitted for the first time. (Database)
  3. Each time someone tries to submit the form the random token will get updated, it will be unique since it will be based on timestamp. Therefore if user submits form by just copying the token and POST data without going through the form, your code should check on PHP side whether that token already exists in the Database or not. If it does prompt user with friendly error message or redirect. If it does not then update the old token to hold the new token.

Token can be saved either in DB or Session depending what you want to do with them.

Sign up to request clarification or add additional context in comments.

1 Comment

Is this going to work in practice? When am i going to update the token? I have lot of users going to submit the form simultaneously
0

You're basically wanting to guard against CSRF. As GGio said, a session-based token is the best way to achieve this.

if (!isset($_SESSION['token'])) {
    $token = sha1(uniqid(rand(), true) . $_SESSION['user_id']);
    $_SESSION['token'] = $token;
    $_SESSION['token_time'] = time();
}
else{
    $token = $_SESSION['token'];
}

In your form element:

<input type = "hidden" name = "token" value = "<?php echo $token; ?>" >

Before you process the form:

if(isset($_SESSION['token']) && isset($_POST['token']) && $_POST['token'] === $_SESSION['token']){
    //user submitted the form correctly
}
else{
    //something isn't right
}

2 Comments

I can just copy the token html-element. And bypass the form. This will not work.
Check the referrer as well? There's no sure-fire way of preventing this sort of thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.