Go Back   CodingForums.com > :: Server side development > PHP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 11-28-2012, 02:21 PM   PM User | #1
Jodzzz
New Coder

 
Join Date: Nov 2012
Posts: 16
Thanks: 2
Thanked 0 Times in 0 Posts
Jodzzz is an unknown quantity at this point
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
Jodzzz is offline   Reply With Quote
Old 11-28-2012, 06:22 PM   PM User | #2
CHEWX
Regular Coder

 
Join Date: Dec 2010
Posts: 124
Thanks: 17
Thanked 6 Times in 6 Posts
CHEWX is an unknown quantity at this point
Am I being blind or can I not see the private key in that code.
CHEWX is offline   Reply With Quote
Old 11-29-2012, 02:21 AM   PM User | #3
Inigoesdr
Super Moderator


 
Inigoesdr's Avatar
 
Join Date: Mar 2007
Location: Florida, USA
Posts: 3,604
Thanks: 2
Thanked 399 Times in 392 Posts
Inigoesdr is a jewel in the roughInigoesdr is a jewel in the roughInigoesdr is a jewel in the rough
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).
Inigoesdr is offline   Reply With Quote
Old 11-29-2012, 09:57 AM   PM User | #4
Jodzzz
New Coder

 
Join Date: Nov 2012
Posts: 16
Thanks: 2
Thanked 0 Times in 0 Posts
Jodzzz is an unknown quantity at this point
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..
Jodzzz is offline   Reply With Quote
Old 11-30-2012, 12:33 AM   PM User | #5
Inigoesdr
Super Moderator


 
Inigoesdr's Avatar
 
Join Date: Mar 2007
Location: Florida, USA
Posts: 3,604
Thanks: 2
Thanked 399 Times in 392 Posts
Inigoesdr is a jewel in the roughInigoesdr is a jewel in the roughInigoesdr is a jewel in the rough
Your private key is meant to be kept private.
Inigoesdr is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 09:23 AM.


Advertisement
Log in to turn off these ads.