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

Dennis Hackethal
  • 13,662
  • 12
  • 66
  • 115
  • the error message suggests that the `"[]" syntax` is wrong. Try removing the empty brackets. And `=` is for assignments. `==` is for conditions. – Nadir Sampaoli May 08 '12 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. – symcbean May 08 '12 at 12:07

3 Answers3

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;
VisioN
  • 143,310
  • 32
  • 282
  • 281
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.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
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:

Community
  • 1
  • 1
Petah
  • 45,477
  • 28
  • 157
  • 213