向表单添加验证码



我正在创建一个带有验证码的php联系表单,但我无法弄清楚如何实际获得验证码图像显示。到目前为止,它只显示了一个关闭按钮x和单词CAPTCHA图像代替真实的图像。我还想将name字段拆分为同一行上的First name和Last name两个字段。非常感谢任何帮助。下面是html代码和php代码:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Formify</title>
    <link href="style/default.css" rel="stylesheet" type="text/css" />
    <script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
    <script src="js/ajaxfileupload.js" type="text/javascript"></script>
    <script src="js/formify.js" type="text/javascript"></script>
</head>
<body>
    <div id="wrapper">
        <!-- header start -->
        <div id="header">
            <a href="#">
                <img src="images/logo.png" style="display: none" alt="Formify Logo" /></a>
        </div>
        <!-- header end -->
        <!-- content start -->
        <form action="" method="POST" enctype="multipart/form-data">
        <div id="content">
            <div class="switcher">
                <select name="form-types" id="form-types">
                    <option value="none">Select Form Type</option>
                    <option value="question-form" selected="true">Ask a Question Form</option>
                    <option value="contact-form">Contact Form</option>
                    <option value="feedback-form">Feedback Form</option>
                </select>
            </div>
            <form>
            <div class="form-fields">
                <!-- Ask a Question Form -->
                <div id="question-form" class="form">
                    <h1>
                        Ask a Question Form</h1>
                    <table cellpadding="5" cellspacing="0">
                        <tr>
                            <td>
                                <input type="text" id="qf-full-name" value="Full Name" class="required" title="Full Name" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <input type="text" id="qf-email-address" value="Email Address" class="email-address"
                                    title="Email Address" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <input type="text" id="qf-subject" value="Subject" title="Subject" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <input type="file" id="attachment" name="attachment" />
                                <img src="images/sending.gif" alt="uploading..." id="uploading" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <textarea rows="7" id="qf-message"></textarea>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <input type="checkbox" id="qf-cc" />
                                CC this message to yourself
                            </td>
                        </tr>
                    </table>
                </div>
                <!-- Contact Form -->
                <div id="contact-form" class="form hidden">
                    <h1>
                        Contact Form</h1>
                    <table cellpadding="5" cellspacing="0">
                        <tr>
                            <td>
                                <input type="text" id="cf-full-name" value="Full Name" title="Full Name" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <input type="text" id="cf-email-address" value="Email Address" class="email-address"
                                    title="Email Address" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <input type="text" id="cf-telephone" value="Telephone" class="telephone" title="Telephone" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <input type="text" id="cf-website" value="Website" title="Website" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <input type="text" id="cf-subject" value="Subject" title="Subject" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <textarea rows="7" id="cf-message"></textarea>
                            </td>
                        </tr>
                    </table>
                </div>
                <!-- Feedback Form -->
                <div id="feedback-form" class="form hidden">
                    <h1>
                        Feedback Form</h1>
                    <table cellpadding="5" cellspacing="0">
                        <tr>
                            <td>
                                <input type="text" id="ff-full-name" value="Full Name" title="Full Name" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <input type="text" id="ff-email-address" value="Email Address" class="email-address"
                                    title="Email Address" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <input type="text" id="ff-telephone" value="Telephone" class="telephone" title="Telephone" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <select id="ff-options">
                                    <option>I have a suggestion</option>
                                    <option>I want to register a complain</option>
                                    <option>I am not satisfied</option>
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <input type="checkbox" id="ff-other" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <input type="text" id="ff-subject" value="Subject" title="Subject" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <textarea rows="7" id="ff-message"></textarea>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <input type="checkbox" id="ff-keep-anonymous" />
                                Keep anonymous
                            </td>
                        </tr>
                    </table>
                </div>
                <table>
                <tr>
                    <td>
                        <img id="siimage" style="border: 1px solid #000; margin-right: 15px" src="securimage/securimage_show.php?sid=<?php echo md5(uniqid()) ?>"
                            alt="CAPTCHA Image" align="left">
                        <object type="application/x-shockwave-flash" data="securimage/securimage_play.swf?audio_file=securimage/securimage_play.php&amp;bgColor1=#fff&amp;bgColor2=#fff&amp;iconColor=#777&amp;borderWidth=1&amp;borderColor=#000"
                            height="32" width="32">
                            <param name="movie" value="securimage/securimage_play.swf?audio_file=securimage/securimage_play.php&amp;bgColor1=#fff&amp;bgColor2=#fff&amp;iconColor=#777&amp;borderWidth=1&amp;borderColor=#000">
                        </object>
                        &nbsp; <a tabindex="-1" style="border-style: none;" href="#" title="Refresh Image"
                            onclick="document.getElementById('siimage').src = 'securimage/securimage_show.php?sid=' + Math.random(); this.blur(); return false">
                            <img src="securimage/images/refresh.png" id="refresh-captcha" alt="Reload Image"
                                onclick="this.blur()" align="bottom" border="0"></a><br />
                        <strong>Enter Code*:</strong><br />
                        <input type="text" id="captcha" size="12" maxlength="8" autocomplete='off' />
                    </td>
                </tr>
                <tr>
                    <td>
                        <input type="submit" class="large button green" value="Send Message" />
                        <label class="submit-message">
                        </label>
                        <img class="submit-sending" src="images/sending.gif" alt="sending..." />
                    </td>
                </tr>
            </table>
        </div>
        </form>
        <!-- content end -->
    </div>
    </form>
    </div>
</body>
</html>

    <?php
    require("class.phpmailer.php");
    //Variables Declaration
    $name = "the Submitter";
    $email_subject = "Feed Back";
    $Email_msg ="A visitor submitted the following :n";
    $Email_to = "you@yourSite.com"; // the one that recieves the email
    $email_from = "someone@someone.net";
    $dir = "uploads/$filename";
    chmod("uploads",0777);
    $attachments = array();
    checkType();
    //------Check TYPE------\  
    function checkType() {  
        while(list($key,$value) = each($_FILES[attachment][type])){
            strtolower($value);
            if($value != "image/jpeg" AND  $value != "image/pjpeg" AND $value != "") {
                exit('Sorry , current format is <b>'.($value).'</b> ,only Jpeg or jpg are allowed.') ;
            }
        }
        checkSize();

    }
    //-------END OF Check TYPE--------\

    //---CheckSizeFunction ---\
    function checkSize(){
        global $result, $MV ,$errors,$BackLink;
        while(list($key,$value) = each($_FILES[attachment][size]))
           {
            $maxSize = 5000000;
                    if(!empty($value)){
                        if ($value > $maxSize) {
                            echo"Sorry this is a very big file .. max file size is $maxSize Bytes = 5 MB";
                            exit();
                        }
                        else {
                        $result =  "File size is ok :)<br>";
                        }
            }
          } 
            uploadFile();
    }
    //-------END OF Check Size--------\


    //==============upload File Function============\
    function uploadFile() {
        global $attachments;
        while(list($key,$value) = each($_FILES[attachment][name]))
                    {
                        if(!empty($value))
                        {
                                $filename = $value;
                                array_push($attachments, $filename);
                                $dir = "uploads/$filename";
                                chmod("uploads",0777);
                                 $success = copy($_FILES[attachment][tmp_name][$key], $dir);
                        }
                    }
                                   if ($success) {
                                    echo " Files Uploaded Successfully<BR>";
                                    SendIt();
                                        }else {
                                                exit("Sorry the server was unable to upload the files...");
                                            }
    }



    //======================================================================== PHP Mailer With ATtachment Func ===============================\
    function readMailSettings()
    {
        global $SMTPSERVER,$SMTPPORT,$SMTPUSER,$SMTPPASSWORD,$ADMINEMAIL,$ADMINNAME;
        $file  = fopen('mail.config','r');
        while(!feof($file))
        {
            $setting = explode(':',fgets($file));
            //print_r($setting);    
            switch($setting[0])
            {
                case 'SMTPSERVER':
                    $SMPTSERVER = $setting[1];
                    break;
                case 'SMTPPORT':
                    $SMTPPORT = $setting[1];
                    break;
                case 'SMTPUSER':
                    $SMPTUSER = $setting[1];
                    break;
                case 'SMTPPASSWORD':
                    $SMTPPASSWORD  = $setting[1];
                    break;
                case 'ADMINEMAIL':
                    $ADMINEMAIL = $setting[1];          
                    break;
                case 'ADMINNAME':
                    $ADMINNAME = $setting[1];
                    break;          
            }   
        }
    }
    function SendIt() {

            global $attachments,$name,$Email_to,$Email_msg,$email_subject,$email_from;
            $mail = new PHPMailer();

            $mail->IsSMTP();// send via SMTP
            $mail->Host     = "localhost"; // SMTP servers
            $mail->SMTPAuth = false; // turn on/off SMTP authentication
            $mail->From     = $email_from;
            $mail->FromName = $name;
            $mail->AddAddress($Email_to); 
            $mail->AddReplyTo($email_from);
            $mail->WordWrap = 50;// set word wrap
                foreach($attachments as $key => $value) {  //loop the Attachments to be added ...
                $mail->AddAttachment("uploads"."/".$value);
            }
            $mail->Body = $Email_msg."Name : ".$name."n";
            $mail->IsHTML(false);// send as HTML
            $mail->Subject  =  $email_subject;
            if(!$mail->Send())
            {
               echo "Message was not sent <p>";
               echo "Mailer Error: " . $mail->ErrorInfo;
               exit;
            }
            echo "Message has been sent";
            // after mail is sent with attachments , delete the images on server ...
            foreach($attachments as $key => $value) {//remove the uploaded files ..
                    unlink("uploads"."/".$value);
                                    }

    }

    ?>
    <?php
        $error = "";
        $msg = "";
        $fileElementName = 'attachment';
        chmod("uploads",0777);
        if(!empty($_FILES[$fileElementName]['error']))
        {
            switch($_FILES[$fileElementName]['error'])
            {
                case '1':
                    $error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
                    break;
                case '2':
                    $error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
                    break;
                case '3':
                    $error = 'The uploaded file was only partially uploaded';
                    break;
                case '4':
                    $error = 'No file was uploaded.';
                    break;
                case '6':
                    $error = 'Missing a temporary folder';
                    break;
                case '7':
                    $error = 'Failed to write file to disk';
                    break;
                case '8':
                    $error = 'File upload stopped by extension';
                    break;
                case '999':
                default:
                    $error = 'No error code avaiable';
            }
        }elseif(empty($_FILES['attachment']['tmp_name']) || $_FILES['attachment']['tmp_name'] == 'none')
        {
            $error = 'No file was uploaded..';
        }else 
        {   
                if (file_exists("uploads/" . $_FILES["attachment"]["name"]))
                {
                    //echo $_FILES["attachment"]["name"] . " already exists. ";
                    @unlink("uploads"."/".$_FILES["attachment"]["name"]);
                }
                      $msg = $_FILES["attachment"]["name"];
                      move_uploaded_file($_FILES["attachment"]["tmp_name"],
                      "uploads/" . $_FILES["attachment"]["name"]);

        }       
        echo "{";
        echo                "error: '" . $error . "',n";
        echo                "attachment: '" . $msg . "'n";
        echo "}";
    ?>
    <?php
    session_start();
    require_once('phpmailer/class.phpmailer.php');
    $SMTPSERVER='';
    $SMTPPORT='';
    $SMTPUSER='';
    $SMTPPASSWORD='';
    $ADMINEMAIL='';
    $ADMINNAME='';
    $from = $_POST['email'];
    $fullName= $_POST['from'];
    $subject= $_POST['subject'];
    $message= $_POST['message'];
    $cc = $_POST['cc'];
    $anonymous = $_POST['anonymous'];
    $attachment = $_POST['attachment'];
    $_SESSION['ctform'] = array(); // re-initialize the form session data
     $errors = array();  // initialize empty error array
    // Only try to validate the captcha if the form has no errors
        // This is especially important for ajax calls
    $captcha  = $_POST['code'];
    if (sizeof($errors) == 0) {
        require_once dirname(__FILE__) . '/securimage/securimage.php';
            $securimage = new Securimage();    
         if ($securimage->check($captcha) == false) {
            $errors['captcha_error'] = 'Incorrect security code entered<br />';
        }
         //echo 'Incorrect security code entered<br />';
    }
    if (sizeof($errors) == 0) {
      echo smtpmailer($from,$fullName,$subject,$message,$anonymous,$attachment);  
    }
    else
    {
        echo $errors['captcha_error'];
    }
    function smtpmailer($from, $from_name, $subject, $body,$anonymous,$attachment) { 
    global $SMTPSERVER,$SMTPPORT,$SMTPUSER,$SMTPPASSWORD,$ADMINEMAIL,$ADMINNAME;
    global $cc;
        global $error;
        readMailSettings(); 
        $to = $ADMINEMAIL;
        $mail = new PHPMailer();  // create a new object
        $mail->IsSMTP(); // enable SMTP
        $mail->IsMail();//enable email through php mail();
        //$mail->SMTPDebug = 0;  // debugging: 1 = errors and messages, 2 = messages only
        //$mail->SMTPAuth = true;  // authentication enabled
        //$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
        //$mail->Host = $SMTPSERVER;
        //$mail->Port = $SMTPPORT; 
        //$mail->Username = $SMTPUSER;
        //$mail->Password = $SMTPPASSWORD;   
        $mail->IsHTML(true);
        if($anonymous == 'true')
        {
            $from= $to;
            $from_name = 'Anonymous';
        }
        $mail->SetFrom($from, $from_name);      
        $body .= "Is Anonymous: " . $anonymous;
        $mail->Subject = $subject;
        $mail->Body = $body;
        $mail->AddAddress($to);
        $attachmentFailed = false;
        $attachmentPath = "uploads"."/".$attachment;
        if(!empty($attachment))
        {       
            chmod("uploads",0777);
            if(file_exists($attachmentPath))
                $mail->AddAttachment($attachmentPath, $attachment);
            else
            {
                echo "Attachement failed";
                $attachmentFailed = true;
            }
        }
        if(!$attachmentFailed)
        {
            if(!empty($cc))
                $mail->AddCC($from);
            if(!$mail->Send()) {
              if(!empty($attachment))
                 //echo  'Mail attachment error: '.$mail->ErrorInfo; 
                 echo "Unable to attach your file at the moment, please try again later.";
              else
                 return false;
            } else {
                if(!empty($attachment))
                    unlink($attachmentPath);
                return true;
            }
        }
    }
    function readMailSettings()
    {
        global $SMTPSERVER,$SMTPPORT,$SMTPUSER,$SMTPPASSWORD,$ADMINEMAIL,$ADMINNAME;
        $file  = fopen('mail.config','r');
        while(!feof($file))
        {
            $setting = explode(':',fgets($file));
            //print_r($setting);    
            switch($setting[0])
            {
                case 'SMTPSERVER':
                    $SMPTSERVER = $setting[1];
                    break;
                case 'SMTPPORT':
                    $SMTPPORT = $setting[1];
                    break;
                case 'SMTPUSER':
                    $SMPTUSER = $setting[1];
                    break;
                case 'SMTPPASSWORD':
                    $SMTPPASSWORD  = $setting[1];
                    break;
                case 'ADMINEMAIL':
                    $ADMINEMAIL = $setting[1];          
                    break;
                case 'ADMINNAME':
                    $ADMINNAME = $setting[1];
                    break;          
            }   
        }
    }
    ?>
    <?php
    function multi_attach_mail($to, $files, $sendermail){
        // email fields: to, from, subject, and so on
        $from = "Files attach <".$sendermail.">"; 
        $subject = date("d.M H:i")." F=".count($files); 
        $message = date("Y.m.d H:i:s")."n".count($files)." attachments";
        $headers = "From: $from";
        // boundary 
        $semi_rand = md5(time()); 
        $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 
        // headers for attachment 
        $headers .= "nMIME-Version: 1.0n" . "Content-Type: multipart/mixed;n" . " boundary="{$mime_boundary}""; 
        // multipart boundary 
        $message = "--{$mime_boundary}n" . "Content-Type: text/plain; charset="iso-8859-1"n" .
        "Content-Transfer-Encoding: 7bitnn" . $message . "nn"; 
        // preparing attachments
        for($i=0;$i<count($files);$i++){
            if(is_file($files[$i])){
                $message .= "--{$mime_boundary}n";
                $fp =    @fopen($files[$i],"rb");
            $data =    @fread($fp,filesize($files[$i]));
                        @fclose($fp);
                $data = chunk_split(base64_encode($data));
                $message .= "Content-Type: application/octet-stream; name="".basename($files[$i]).""n" . 
                "Content-Description: ".basename($files[$i])."n" .
                "Content-Disposition: attachment;n" . " filename="".basename($files[$i]).""; size=".filesize($files[$i]).";n" . 
                "Content-Transfer-Encoding: base64nn" . $data . "nn";
                }
            }
        $message .= "--{$mime_boundary}--";
        $returnpath = "-f" . $sendermail;
        $ok = @mail($to, $subject, $message, $headers, $returnpath); 
        if($ok){ return $i; } else { return 0; }
        }
    ?>

该图像可能不会出现,因为captcha图像的路径是securimage/securimage_show.php,这可能相对于您的表单位置不正确。

/securimage/securimage_show.php这样的名字可能更合适。也检查,以确保captcha图像显示正确,并在您的系统上工作通过转到securimage/example_form.php

Securimage还提供了一种方法,可以为您呈现captcha html,这可能会更好地工作。在这种情况下,试试:

<?php
  // show captcha HTML using Securimage::getCaptchaHtml()
  require_once 'securimage.php'; // CHANGE THIS TO THE CORRECT PATH
  $options = array();
  echo Securimage::getCaptchaHtml($options);
?>

相关内容

  • 没有找到相关文章

最新更新