0

I want to achieve that a user cannot send the same input twice. I use a php script to submit user input.

My idea is to save his inputs in a session array and each time that he submits something check through the array if it matches one of the things he already submitted before.

The code looks like this:

    //Compare post with what user has posted so far; if the same, exit (spam protection)
    foreach($_SESSION['postarray'][] as $postarray) if($post=$postarray) exit;

    //Save post in session of all other posts
    $_SESSION['postarray'][]=$post;

I get the following error:

Fatal error: Cannot use [] for reading in /Applications/XAMPP/xamppfiles/htdocs/postish/action/post.php on line 32 (which refers to the line with the foreach() loop)

Even after changing the function to only $_SESSION['post array'], it doesn't work either.

Any help much appreciated :)

Dennis

2
  • the error message suggests that the "[]" syntax is wrong. Try removing the empty brackets. And = is for assignments. == is for conditions. Commented May 8, 2012 at 10:24
  • Premise is fundamentally flawed as is method of implementation. How do you deal with an ever-growing session? Why not at the storage tier? I suspect you really want to prevent the user submitting the same instance of a form multiple times - in which case this should be managed at the client. See also CSRF prevention. Commented May 8, 2012 at 12:07

3 Answers 3

4

Operator [] adds a new element to array.

To get elements for foreach loop you have to use it without []:

foreach($_SESSION['postarray'] as $postarray)
    if ($post == $postarray) exit;

And pay attention to comparison operator == which is used to check the equality of the variables.

The better option to check if $post exists in $_SESSION['postarray'] is to use in_array function:

if (in_array($post, $_SESSION['postarray'])) exit;
Sign up to request clarification or add additional context in comments.

Comments

2

You accidentally used the assignment operator = instead of the comparion operator == or ===.

So you need to replace if($post=$postarray) with if($post == $postarray)

You also need to remove the [] in foreach($_SESSION['postarray'][] as $postarray) as [] is only used when inserting a new array element.

Comments

0

If you want to stop a user from sending the same data twice, you need to look into using a nonce (number used once)

There are a few examples:

Comments

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.