如何在php中比较表单数据

时间:2016-02-07 13:53:01

标签: php html css

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;
//}

表单中显示的图像有一些数字。当用户点击发送时,我想比较图像中显示的输入数字并进行比较。

我该怎么做。

2 个答案:

答案 0 :(得分:2)

在表单中,创建隐藏输入:

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

在PHP文件中,您现在可以拥有两个$_POST变量:

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

现在你需要找到图像的关键字:

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

使用密钥值,检查正确的令牌:

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

答案 1 :(得分:0)

您无法传递图片,因为它不是输入元素,您可以使用隐藏的输入元素代替:

<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>

为了使用PHP搜索数组中的图像值,您可以使用in_array

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

编辑:要获取特定索引,请使用@ GrzegorzGajda中的示例&#39;答案