简体   繁体   中英

Method to refresh PNG file without refreshing the whole page

使用imagestring创建一个验证码

Normally i won't write this much code as stackoverflow isn't a coding service but after seeing screenshots of your code in the comments am convinced you have made a fair attempt but in the wrong direction hence the following piece of code is an example guide line of how a captche code should be using PHP and AJAX.

This first file is the image file it is named captche_image.php and should be separate as ajax calls will be made to it:

<?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();

?>

This other file should be your captche page it a combined page of PHP and HTML and i have added minimal CSS to make it visible.

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

Note: The page which the user is been redirected to on success of captche should have a way of verifying that the captche was entered correctly else user can just redirect herself to said page.

As LPK pointed out, you have to change the source of the image via JavaScript in order for the browser to refresh it.

I'm not sure why you were having problems with it, as you indicated in the comments of LPK's answer but maybe you forgot to include the onclick property in the HTML.

Here is an example with a snippet that shows how to do it on a timer, on image click, and on an anchor element being clicked. Also as pointed out in LPK's answer, just set the src attribute to the same thing to reload the same image.

 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; } 
 <img src="http://placehold.it/100x100" id="captchaimage"/> <a id='testBtn'>Click to change captcha image</a> 

For another source on the topic check out this link to the W3 Schools page and you can check out the 'Try it Yourself' link to see yet another example of this in action.

Simple things :

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

Then :

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

So when you click on the image, it'll reload only the image (add the same source to always reload the same image)

EDIT

If you don't want to have to click, you can also set a timer that will reload every x seconds (need an other line of code)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM