Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New Coder
    Join Date
    Nov 2012
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts

    reCaptcha and PHP

    I got this form that sends data to a database, i want to add a captcha which i've done but its not working, it shows up but i doesn't actually work.

    Code:
    <?php 
    $action = (isset($_GET['action']) ? $_GET['action'] : '');
    	
    include("includes/header1.inc.php"); 
    ?>
    	<title>Feock Parish Council Community Page</title>
    	<script type= "text/javascript">
    var RecaptchaOptions = {
    theme: 'white'
    };
    </script>
    
    <?php 
    
    
    include("includes/header2.inc.php"); 
    require("control/config.inc.php");
    require($databaseClassSource);
    $db = new Database($theDB);
    	
    	// Initalise variables
    	$complete = false;
    		
    	// Define functions
    	function exc_not_null($value) {
    		if (is_array($value)) {
    			if (sizeof($value) > 0) {
    				return true;
    			} else {
    				return false;
    			}
    			} else {
    				if ( (is_string($value) || is_int($value)) && ($value != '') && ($value != 'NULL') && (strlen(trim($value)) > 0)) {
    				return true;
    			} else {
    				return false;
    			}
    		}
    	}
    		
    	function exc_db_input($string, $link = 'db_link') {
    		if (function_exists('mysql_escape_string')) {
    			return mysql_escape_string($string);
    		}
    	return addslashes($string);
    	}
    
    	function exc_db_prepare_input($string) {
    		if (is_string($string)) {
    			return trim(stripslashes($string));
    		} elseif (is_array($string)) {
    			reset($string);
    			while (list($key, $value) = each($string)) {
    			$string[$key] = exc_db_prepare_input($value);
    		}
    			return $string;
    		} else {
    			return $string;
    		}
    	}
    	
    	// Fetch post vars
    	$title = exc_db_prepare_input($_POST['title']);
    	$author_name = exc_db_prepare_input($_POST['author_name']);
    	$author_phone = exc_db_prepare_input($_POST['author_phone']);
    	$contact_name = exc_db_prepare_input($_POST['contact_name']);
    	$contact_phone = exc_db_prepare_input($_POST['contact_phone']);
    	$text = preg_replace("(\r\n\r\n|\n\n|\r\r)", "</p><p>", $_POST['text']);
    	$text = exc_db_prepare_input($_POST['text']);
    	
    	if ($action == 'addnow') {  //----------------------------------------------------------------- ADDNOW
    		
    		// Validate POTS vars
    		if (!exc_not_null($title)) {
    		$error = true;
    		$title_error = true;
    		}
    		if (!exc_not_null($author_name)) {
    		$error = true;
    		$author_name_error = true;
    		}
    		if (!exc_not_null($author_phone)) {
    		$error = true;
    		$author_phone_error = true;
    		}
    		if (!exc_not_null($text)) {
    		$error = true;
    		$text_error = true;
    		}
    		
    		// Generate unique filename
    		$origfilename = str_replace(" ", "_",$_FILES["image"]["name"]);
    		if (exc_not_null($origfilename)) {
    			$uniq = uniqid('news_',false);
    			$uniqfilename = $uniq . '_' . $origfilename;
    		} else {
    			$uniqfilename = '';
    		}
    		
    		// Check image file does not exist
    		if (is_file("images/community/news/" . $uniqfilename))
    		{
    			$error = true;
    			$file_exists_error = true;
    		}
    		// the file is greater than a meg
    		else if ($_FILES["image"]["size"] > 1048576)
    		{
    			$error = true;
    			$file_size_error = true;
    		}
    		// file has been uploaded sucessfully 
    		else if ($_FILES["image"]["name"] == "")
    		{
    			$no_file_error = true;
    		}
    		else
    		{			
    			move_uploaded_file($_FILES["image"]["tmp_name"], "images/community/news/" . $uniqfilename);
    			$flagImg = true;
    		}
    		
    		//Handle errors, if any
    		if ($error == true) {
    			if ($flagImg == true) {
    				unlink("images/community/news/" . $uniqfilename);
    			}
    			
    			$action = 'error';
    		} else { // or if no errors...
    		
    		
    		$image_filename = $uniqfilename;
    
    			$query = "INSERT INTO tblCommunityNews (community_news_title, community_news_author_name, community_news_author_phone, community_news_contact_name, community_news_contact_phone, community_news_text, community_news_image) VALUES ('";
    			$query .= exc_db_input($title) . "', '";
    			$query .= exc_db_input($author_name) . "', '";
    			$query .= exc_db_input($author_phone) . "', '";
    			$query .= exc_db_input($contact_name) . "', '";
    			$query .= exc_db_input($contact_phone) . "', '";
    			$query .= exc_db_input($text) . "', '";
    			$query .= $image_filename . "');";
    
    			//$db = new Database($theDB);
    			$db->query($query);
    			$db->close();
    
    			// Email council to approve			 
    			$email_message = "A new community news item has been added and requires approval.\n";	
    			$headers = 'From: info@feockpc.com' . "\r\n".
    			'Bcc: jodie@cnx-solutions.com' . "\r\n" .
    			'Reply-To: info@feockpc.com' . "\r\n" .
    			'X-Mailer: PHP/' . phpversion();
    			mail('alan@feockpc.com', 'New Community Content', $email_message, $headers); 
    
    			
    			// all is well - say so!
    			print "<h1>COMMUNITY NEWS ITEM ADDED</h1>\n";
    			print "<p class=\"centered\">The news item was successfully added to the system and is awaiting approval by our moderators.</strong></p>\n";
    			print "<p class=\"centered\"><a href=\"community-news.php\">Click here</a> to return to the community news listings.</strong></p>\n";
    			
    			$complete = true;
    		
    		}
    		
    	}
    
    
    	if (!$complete == true) {
    	?>
    		<script type="text/JavaScript" src="javascript/picker/picker.js"></script>
    		<link rel="stylesheet" type="text/css" href="javascript/picker/picker.css" media="screen" />
    
    		<h1>ADD YOUR NEWS</h1>
    		<P>Fill in the form below to submit your news to our community pages. Once you have submitted your news it will be sent to our moderators and will be displayed to the public once it is approved.</p>
    
    		<form method="post" action="community-news-add.php?action=addnow" enctype="multipart/form-data" >
    
    		<h2>Title</h2>
    		<?php if ($title_error == true) { print "<p class=\"formerror\">Please add a title to your news.</p>\n"; } ?>
    		<p><input name="title" size="45" maxlength="50" <?php if(exc_not_null($title)) { echo 'value="' . $title . '"'; } ?> /></p>
    
    		<h2>Author</h2>
    		<p>This is for our refernce only and is not visible to public.</p>
    		<?php if ($author_name_error == true) { print "<p class=\"formerror\">Please enter your name in the box below.</p>\n"; } ?>
    		<p><input name="author_name" size="45" maxlength="50" <?php if(exc_not_null($author_name)) { echo 'value="' . $author_name . '"'; } ?> /></p>
    
    		<h2>Phone Number for Author</h2>
    		<p>This is for our refernce only and is not visible to public.</p>
    		<?php if ($author_phone_error == true) { print "<p class=\"formerror\">You must supply your contact number, in case we need to contact you. <br />This number will never be given to the public without your consent.</p>\n"; } ?>
    		<p><input name="author_phone" size="45" maxlength="20" <?php if(exc_not_null($author_phone)) { echo 'value="' . $author_phone . '"'; } ?> /></p>
    
    		<h2>Name of Public Contact (Optional)</h2>
    		<p><input name="contact_name" size="45" maxlength="50" <?php if(exc_not_null($contact_name)) { echo 'value="' . $contact_name . '"'; } ?> /></p>
    
    		<h2>Phone Number for Public Contact (Optional)</h2>
    		<p><input name="contact_phone" size="45" maxlength="20" <?php if(exc_not_null($contact_phone)) { echo 'value="' . $contact_phone . '"'; } ?> /></p>
    
    		<h2>Text</h2>
    		<?php if ($text_error == true) { print "<p class=\"formerror\">Please type your news in the box below.</p>\n"; } ?>
    		<p><textarea cols="50" rows="10" name="text"> <?php if(exc_not_null($text)) { echo $text; } ?></textarea></p>
    
    		<h2>Image (Optional)</h2>
    		<p>Your image should be square in its dimentions and less than 1MB in size.</p>
    		<?php
    		if ($file_exists_error == true) { print "<p class=\"formerror\">Error: A file with this name already exists on the server. Please change the filename and try again.</p>\n"; }
    		if ($file_size_error == true) { print "<p class=\"formerror\">Error: File size too large.</p>\n"; }
    		if ($no_file_error == true) { print "<p class=\"formerror\">Warning: No file uploaded.</p>\n"; }
    		?>
    		<p><input type="file" name="image" /></p>
    
    		<p><input type="submit" value="&nbsp;Save&nbsp;" class="normal" /></p>		
    		</form><?php
    require_once('recaptchalib.php');
    $publickey = "6LcYbswSAAAAAGO0LKVW1stPQS6bdeFnYKPrhYMN";
    echo recaptcha_get_html($publickey);
    ?>
    	<?php
    	}
    	
    	
    include("includes/footer.inc.php"); ?>
    Last edited by Jodzzz; 11-28-2012 at 04:12 PM. Reason: wrong title

  • #2
    Regular Coder
    Join Date
    Dec 2010
    Posts
    134
    Thanks
    17
    Thanked 6 Times in 6 Posts
    Am I being blind or can I not see the private key in that code.

  • #3
    Super Moderator Inigoesdr's Avatar
    Join Date
    Mar 2007
    Location
    Florida, USA
    Posts
    3,638
    Thanks
    2
    Thanked 404 Times in 396 Posts
    There are 2 parts to using reCAPTCHA. The first part is adding the reCAPTCHA field to your form, which it looks like you've done. The second part is checking the answer that people submit against the image.

    That portion needs to be added to your code that you execute to handle the form submission (during your validation, prior to inserting it in to the database. The reCAPTCHA site has some pretty useful documentation about both steps and some sample code you can start with (see the "Server Side" section for the part you are missing).

  • #4
    New Coder
    Join Date
    Nov 2012
    Posts
    16
    Thanks
    2
    Thanked 0 Times in 0 Posts
    All sorted, here's the code for reference. I

    PHP Code:

    <?php 
    $action 
    = (isset($_GET['action']) ? $_GET['action'] : '');
        
    include(
    "includes/header1.inc.php"); 
    ?>
        <title>Feock Parish Council Community Page</title>
        <script type= "text/javascript">
    var RecaptchaOptions = {
    theme: 'white'
    };
    </script>



    <?php 


    include("includes/header2.inc.php"); 
    require(
    "control/config.inc.php");
    require(
    $databaseClassSource);
    $db = new Database($theDB);
        
        
    // Initalise variables
        
    $complete false;
            
        
    // Define functions
        
    function exc_not_null($value) {
            if (
    is_array($value)) {
                if (
    sizeof($value) > 0) {
                    return 
    true;
                } else {
                    return 
    false;
                }
                } else {
                    if ( (
    is_string($value) || is_int($value)) && ($value != '') && ($value != 'NULL') && (strlen(trim($value)) > 0)) {
                    return 
    true;
                } else {
                    return 
    false;
                }
            }
        }
            
        function 
    exc_db_input($string$link 'db_link') {
            if (
    function_exists('mysql_escape_string')) {
                return 
    mysql_escape_string($string);
            }
        return 
    addslashes($string);
        }

        function 
    exc_db_prepare_input($string) {
            if (
    is_string($string)) {
                return 
    trim(stripslashes($string));
            } elseif (
    is_array($string)) {
                
    reset($string);
                while (list(
    $key$value) = each($string)) {
                
    $string[$key] = exc_db_prepare_input($value);
            }
                return 
    $string;
            } else {
                return 
    $string;
            }
        }
        
        
    // Fetch post vars
        
    $title exc_db_prepare_input($_POST['title']);
        
    $author_name exc_db_prepare_input($_POST['author_name']);
        
    $author_phone exc_db_prepare_input($_POST['author_phone']);
        
    $contact_name exc_db_prepare_input($_POST['contact_name']);
        
    $contact_phone exc_db_prepare_input($_POST['contact_phone']);
        
    $text preg_replace("(\r\n\r\n|\n\n|\r\r)""</p><p>"$_POST['text']);
        
    $text exc_db_prepare_input($_POST['text']);
        
        if (
    $action == 'addnow') {  //----------------------------------------------------------------- ADDNOW
            
      
    require_once('recaptchalib.php');
      
    $privatekey "YOURPRIVATEKEYHERE";
      
    $resp recaptcha_check_answer ($privatekey,
                                    
    $_SERVER["REMOTE_ADDR"],
                                    
    $_POST["recaptcha_challenge_field"],
                                    
    $_POST["recaptcha_response_field"]);

      if (!
    $resp->is_valid) {
        
    // What happens when the CAPTCHA was entered incorrectly
        
    die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
             
    "(reCAPTCHA said: " $resp->error ")");
      } else {
        
    // Your code here to handle a successful verification
      
    }
      
            
    // Validate POTS vars
            
    if (!exc_not_null($title)) {
            
    $error true;
            
    $title_error true;
            }
            if (!
    exc_not_null($author_name)) {
            
    $error true;
            
    $author_name_error true;
            }
            if (!
    exc_not_null($author_phone)) {
            
    $error true;
            
    $author_phone_error true;
            }
            if (!
    exc_not_null($text)) {
            
    $error true;
            
    $text_error true;
            }
            
            
    // Generate unique filename
            
    $origfilename str_replace(" ""_",$_FILES["image"]["name"]);
            if (
    exc_not_null($origfilename)) {
                
    $uniq uniqid('news_',false);
                
    $uniqfilename $uniq '_' $origfilename;
            } else {
                
    $uniqfilename '';
            }
            
            
    // Check image file does not exist
            
    if (is_file("images/community/news/" $uniqfilename))
            {
                
    $error true;
                
    $file_exists_error true;
            }
            
    // the file is greater than a meg
            
    else if ($_FILES["image"]["size"] > 1048576)
            {
                
    $error true;
                
    $file_size_error true;
            }
            
    // file has been uploaded sucessfully 
            
    else if ($_FILES["image"]["name"] == "")
            {
                
    $no_file_error true;
            }
            else
            {            
                
    move_uploaded_file($_FILES["image"]["tmp_name"], "images/community/news/" $uniqfilename);
                
    $flagImg true;
            }
            
            
    //Handle errors, if any
            
    if ($error == true) {
                if (
    $flagImg == true) {
                    
    unlink("images/community/news/" $uniqfilename);
                }
                
                
    $action 'error';
            } else { 
    // or if no errors...
            
            
            
    $image_filename $uniqfilename;

                
    $query "INSERT INTO tblCommunityNews (community_news_title, community_news_author_name, community_news_author_phone, community_news_contact_name, community_news_contact_phone, community_news_text, community_news_image) VALUES ('";
                
    $query .= exc_db_input($title) . "', '";
                
    $query .= exc_db_input($author_name) . "', '";
                
    $query .= exc_db_input($author_phone) . "', '";
                
    $query .= exc_db_input($contact_name) . "', '";
                
    $query .= exc_db_input($contact_phone) . "', '";
                
    $query .= exc_db_input($text) . "', '";
                
    $query .= $image_filename "');";

                
    //$db = new Database($theDB);
                
    $db->query($query);
                
    $db->close();

                
    // Email council to approve             
                
    $email_message "A new community news item has been added and requires approval.\n";    
                
    $headers 'From: info@feockpc.com' "\r\n".
                
    'Bcc: jodie@cnx-solutions.com' "\r\n" .
                
    'Reply-To: info@feockpc.com' "\r\n" .
                
    'X-Mailer: PHP/' phpversion();
                
    mail('alan@feockpc.com''New Community Content'$email_message$headers); 

                
                
    // all is well - say so!
                
    print "<h1>COMMUNITY NEWS ITEM ADDED</h1>\n";
                print 
    "<p class=\"centered\">The news item was successfully added to the system and is awaiting approval by our moderators.</strong></p>\n";
                print 
    "<p class=\"centered\"><a href=\"community-news.php\">Click here</a> to return to the community news listings.</strong></p>\n";
                
                
    $complete true;
            
            }
            
        }


        if (!
    $complete == true) {
        
    ?>
            <script type="text/JavaScript" src="javascript/picker/picker.js"></script>
            <link rel="stylesheet" type="text/css" href="javascript/picker/picker.css" media="screen" />

            <h1>ADD YOUR NEWS</h1>
            <P>Fill in the form below to submit your news to our community pages. Once you have submitted your news it will be sent to our moderators and will be displayed to the public once it is approved.</p>

            <form method="post" action="community-news-add.php?action=addnow" enctype="multipart/form-data" >

            <h2>Title</h2>
            <?php if ($title_error == true) { print "<p class=\"formerror\">Please add a title to your news.</p>\n"; } ?>
            <p><input name="title" size="45" maxlength="50" <?php if(exc_not_null($title)) { echo 'value="' $title '"'; } ?> /></p>

            <h2>Author</h2>
            <p>This is for our refernce only and is not visible to public.</p>
            <?php if ($author_name_error == true) { print "<p class=\"formerror\">Please enter your name in the box below.</p>\n"; } ?>
            <p><input name="author_name" size="45" maxlength="50" <?php if(exc_not_null($author_name)) { echo 'value="' $author_name '"'; } ?> /></p>

            <h2>Phone Number for Author</h2>
            <p>This is for our refernce only and is not visible to public.</p>
            <?php if ($author_phone_error == true) { print "<p class=\"formerror\">You must supply your contact number, in case we need to contact you. <br />This number will never be given to the public without your consent.</p>\n"; } ?>
            <p><input name="author_phone" size="45" maxlength="20" <?php if(exc_not_null($author_phone)) { echo 'value="' $author_phone '"'; } ?> /></p>

            <h2>Name of Public Contact (Optional)</h2>
            <p><input name="contact_name" size="45" maxlength="50" <?php if(exc_not_null($contact_name)) { echo 'value="' $contact_name '"'; } ?> /></p>

            <h2>Phone Number for Public Contact (Optional)</h2>
            <p><input name="contact_phone" size="45" maxlength="20" <?php if(exc_not_null($contact_phone)) { echo 'value="' $contact_phone '"'; } ?> /></p>

            <h2>Text</h2>
            <?php if ($text_error == true) { print "<p class=\"formerror\">Please type your news in the box below.</p>\n"; } ?>
            <p><textarea cols="50" rows="10" name="text"> <?php if(exc_not_null($text)) { echo $text; } ?></textarea></p>

            <h2>Image (Optional)</h2>
            <p>Your image should be square in its dimentions and less than 1MB in size.</p>
            <?php
            
    if ($file_exists_error == true) { print "<p class=\"formerror\">Error: A file with this name already exists on the server. Please change the filename and try again.</p>\n"; }
            if (
    $file_size_error == true) { print "<p class=\"formerror\">Error: File size too large.</p>\n"; }
            if (
    $no_file_error == true) { print "<p class=\"formerror\">Warning: No file uploaded.</p>\n"; }
            
    ?>
            <p><input type="file" name="image" /></p>
            <h2>Captcha Form</h2>
            <p>Please enter the words in the box below to prove your human.</p>
    <div style="margin-left:30px;"><p><?php
    require_once('recaptchalib.php');
    $publickey "6LcYbswSAAAAAGO0LKVW1stPQS6bdeFnYKPrhYMN";
    echo 
    recaptcha_get_html($publickey);
    ?></p></div>
            <p><input type="submit" value="Sumbit News" class="normal" /></p>        
            </form>
        <?php
        
    }
        
        
    include(
    "includes/footer.inc.php"); ?>
    You can see i added the validation to ($action=='addnow')
    Last edited by Inigoesdr; 11-30-2012 at 12:32 AM.

  • #5
    Super Moderator Inigoesdr's Avatar
    Join Date
    Mar 2007
    Location
    Florida, USA
    Posts
    3,638
    Thanks
    2
    Thanked 404 Times in 396 Posts
    Your private key is meant to be kept private.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •