Si8
Si8

Reputation: 9235

How to compare form data in php

HTML/PHP:

<form method="post" name="contact" id="frmContact" action="sM.php">
    <img id="main-img" src="theimage/img1.png" name="imageval" />
    <div style="clear: both; padding: 10px 0 0 0; overflow: hidden;">
        Please enter the number(s) from the image above: <input type="text" id="tNum" placeholder="Enter Number(s)" name="numval" />
    </div>
    <input type="submit" value="Send" id="submit" name="submit" class="submit_btn" />
</form>

PHP:

$arrImg = array("img1", "img2", "img3", "img4", "img5", "img6");
$arrImgText = array("56", "342", "34534", "12", "444", "652");

$imgval = trim(strip_tags(stripslashes($_POST['imageval']))); //get the image source that was displayed in the form
$numval = trim(strip_tags(stripslashes($_POST['numval']))); //get the number that the user entered

//if ({arrImg[imgval] == arrImgText[numval]}) {
    //do something;
//}

The image that is displayed in the form has some numbers. When the user hit send, I would like to compare the number that was entered that was displayed in the image and compare.

How can I do that.

Upvotes: 1

Views: 116

Answers (2)

Alon Eitan
Alon Eitan

Reputation: 12025

You can't pass images because it is not an input element, what you could do is use a hidden input element instead:

<form method="post" name="contact" id="frmContact" action="sM.php">
     <img id="main-img" src="theimage/img1.png" />
     <input type="hidden" val="img1" name="imageval" /> <!-- THIS IS THE HIDDEN INPUT ELEMENT THAT WILL BE SUBMITTED -->
     <div style="clear: both; padding: 10px 0 0 0; overflow: hidden;">
          Please enter the number(s) from the image above: <input type="text" id="tNum" placeholder="Enter Number(s)" name="numval" />
     </div>
    <input type="submit" value="Send" id="submit" name="submit" class="submit_btn" />
</form>

In order to search the image value in the array using PHP, you can use in_array:

if( in_array( $_POST['imageval'], $arrImgText ) {
     echo "Image found";
}

Edit: To get the specific index, use the example in @GrzegorzGajda'a answer

Upvotes: 0

Grzegorz Gajda
Grzegorz Gajda

Reputation: 2474

In your form, create hidden input:

<input type="hidden" name="imageval" value="img1" />

In your PHP file you can have now two $_POST variables:

$secretImg = $_POST['imageval'];
$token = $_POST['numval'];

Now you need to find key of image:

$imgKey = array_search($secretImg, $arrImg);

Using the key value, check the proper token:

if ($arrImgText[$imgKey] === $token) {
    // Token is valid
}

Upvotes: 2

Related Questions