在不刷新整个页面的情况下刷新PNG文件的方法

时间:2018-09-26 16:08:28

标签: javascript php html

使用图片字符串创建验证码

3 个答案:

答案 0 :(得分:3)

通常我不会写那么多代码,因为stackoverflow不是编码服务,但是在注释中看到您的代码的屏幕截图后,我确信您已经做出了公平的尝试,但是方向错误,因此下面的代码是有关如何使用PHP和AJAX验证码的示例指南。

第一个文件是图像文件,它的名称为 captche_image.php ,应该分开,因为将对其进行ajax调用:

<?php

session_start();

function captche_generator()
{
    function ct_rand($lenght=6)
    {
        $characters = '0123456789'; $tumble="";
        for ($i=0; $i < $lenght ; $i++) {$tumble .= $characters[mt_rand(0, strlen($characters)-1)];} return $tumble;
    }

    //font file, font size, image text and save text to session
    $fontfile   ='../fonts/JustMeAgainDownHere.ttf';
    $fontsize   =50;
    $text       =ct_rand();
    $_SESSION['captche'] = $text;

    //image size, backgroundcolor, transparent background, textcolor
    $captche_image = imagecreate(180, 50);
    $background_color = imagecolorallocate($captche_image, 255, 255, 255);
    imagecolortransparent($captche_image, $background_color);
    $text_color = imagecolorallocate($captche_image, 0, 0, 0);

    //a loop to create scrambled line in image
    for ($xy=0; $xy <=50 ; $xy++)
    { 
        $x1= rand(1,1000);
        $y1= rand(1,1000);
        $x2= rand(1,100);
        $y2= rand(1,100);
        imageline($captche_image, $x1, $y1, $x2, $y2, $text_color);
    }

    //create image in .png extension
    imagettftext($captche_image, $fontsize, 0, 15, 30, $text_color, $fontfile, $text);
    imagepng($captche_image);

    //set header and return created image
    header("Content-type: image/png");
    return $captche_image;
}

captche_generator();

?>

另一个文件应该是您的验证码页面,它是PHP和HTML的组合页面,并且我添加了最少的CSS以使其可见。

    <?php
ob_start();
session_start();

if(isset($_GET["captche_input"]) && filter_var($_GET["captche_input"], FILTER_VALIDATE_INT))
{
    if($_SESSION['captche'] === $_GET["captche_input"])
    {
        session_destroy();
        ob_flush();
        header("location:./login.php"); //redirect to the login page or any other page you wish
    }
    else
    {
        session_destroy();
        ob_flush();
        echo "<center><p style='padding: 5px;background-color:red;'> Code is Incorrect. Please try Again.</p></center>";
        echo "<script type='text/javascript'> alert('Code is Incorrect. Please try Again.'); </script>";
    }
}
?>

<!DOCTYPE html>
<html>
<style>
    body{
    background-image: url("../images/captche_bg.jpg");
    background-repeat: no-repeat;
    background-size: cover;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-position: right;
    background-attachment: fixed;
    }
    .captcheBoard{
    position: relative;
    display: flex;
    align-items: center;
    flex-basis: 100%;
    flex-direction: column;
    margin-top: 15%;
    text-align: center;
    }
    .captcheBack{
    position: relative;
    height: 90px;
    width: 272px;
    background-image: url('../images/captche_mini.jpg');
    background-repeat: no-repeat;
    background-size: 100%;
    -webkit-background-size: center;
    -moz-background-size: center;
    -o-background-size: center;
    background-position: center;
    border: 0.10em solid coral;
    border-radius: 0.03em;
    }
    .captcheFront{
    position: relative;
    margin-top: 8%;
    }
    .captcheInputBar{
    position: relative;
    margin: 3% 0%;
    border: 0.10em solid coral;
    border-radius: 0.03em;
    font-size: 24px;
    text-align: center;
    }  
</style>
<body>
    <div class="container captcheBoard">

        <div class="captcheBack">
            <div class="captcheFront"><!--captche image is shown here--></div>
        </div>

        <form action="" method="GET">
            <input type="number" class="captcheInputBar" required name="captche_input" pattern="[0-9]{0,}" placeholder="Enter Captche Here" />
            <br>
            <input type="submit" class="Button" name="captche_check" value="Submit" />
        </form>

        <input type="button" class="Button" name="captche_refresh" value="Refresh" onclick="reload_captche()"/>
    </div>

    <script type="text/javascript">
        function reload_captche()
        {
            var xhttp = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');

            xhttp.open("POST", "./captche_image.php", true);
            xhttp.send();

            xhttp.onreadystatechange = function()
            {
                if (this.readyState == 4 && this.status == 200)
                {
                    document.getElementsByClassName("captcheFront")[0].innerHTML = '<img src="./captche_image.php" />';
                }
            }
        }

        window.load = reload_captche();
    </script>
</body>
</html>

请注意:如果验证成功,用户将被重定向至该页面,则应采用一种方式来验证验证码输入是否正确,否则用户可以将自己重定向至该页面。

答案 1 :(得分:2)

LPK指出,您必须通过JavaScript更改图像的来源,以便浏览器刷新图像。

我不确定您为什么会遇到问题,正如您在LPK答案的注释中所指出的那样,但也许您忘记了在HTML中包含To query using the index, use the `.find()` method. ~~~ js db.find({selector:{name:'Alice'}}, function(er, result) { if (er) { throw er; } console.log('Found %d documents with name Alice', result.docs.length); for (var i = 0; i < result.docs.length; i++) { console.log(' Doc id: %s', result.docs[i]._id); } }); ~~~ 属性。

这是一个带有示例的示例,该示例显示了如何在计时器,图像单击以及单击的锚元素上执行此操作。同样如LPK的回答所指出的,只需将onclick属性设置为相同的内容即可重新加载相同的图像。

src
const captchaImage = document.getElementById('captchaimage');

// Change the captcha image after 1 second.
setTimeout(() => {

  captchaImage.src = 'http://placehold.it/125x125';
  
}, 1000);

// Change it on click.
captchaImage.onclick = () => {

  captchaImage.src = 'http://placehold.it/200x200';
  
};

// Change it when another button clicked.
const testBtn = document.getElementById('testBtn');

testBtn.onclick = () => {

  captchaImage.src = 'http://placehold.it/150x150';
  
};
a {
  cursor: pointer;
  background: #e5e5e5;
  padding: 0.5rem;
}

有关该主题的其他来源,请查看指向W3 Schools页面的链接,您可以查看“尝试一下”链接,以查看此操作的另一个示例。

答案 2 :(得分:1)

简单的事情:

<img src="yoursource" id="captchaimage" onclick="actualiser()"/>

然后:

function actualiser() {
document.getElementById("captchaimage").src="yoursource"}

因此,当您单击图像时,它将仅重新加载图像(添加相同的源以始终重新加载相同的图像)

编辑

如果您不想单击,也可以设置一个计时器,每隔x秒重新加载一次(需要另一行代码)