Using Google ReCaptcha - recaptcha

I am keen on using Google ReCaptcha. I have got the captcha on the page using the public key but don't know how to use the private key in my form processor document:
<?php
//SMTP SETTINGS
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.webhost.co.nz'; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = ‘xxxxx#xxxxxxxx.co.nz'; // SMTP username
$mail->Password = ‘xxxxx##xxxxxx’; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable encryption, 'ssl' also accepted
$mail->Port = 465;
$mail->isHTML(true); // Set email format to HTML
//SMTP SETTINGS
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
print_r($_POST);
$mailheader = "From: $email";
$to = "tony#finelinecreative.co.nz"; // Here is email send to
$subject = "Finelinecreative Enquiry";
$message = "Name: $name<br/>Email: $email<br/>Message: $message";
// Send the mail
$mail->From=$mail->Username;
$mail->FromName = 'finelinecreative';
$mail->addAddress($to);
$mail->addReplyTo($email, $email);
$mail->Subject = $subject;
$mail->Body = $message;
$mail->IsHTML(true);
$result = $mail->send();
header('location: http://www.finelinecreative.co.nz/index.php/thanks');
?>
Ideas please?

There's a great tutorial at https://codeforgeek.com/2014/12/google-recaptcha-tutorial/ that explains it pretty well.
In essence, you're checking if the $_POST variable 'g-recaptcha-response' exists (which, by including recaptcha on your form, is sent along with the other values on the form). If it is, you send a file_get_contents call (sending the secret key, the g-recaptcha-response POST value, and the user's IP address). You decode the result of that (which is sent as JSON, and you probably want to access it as key-value pairs), and find out whether the query was successful.
This is the relevant portion of their implementation.
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$secretKey = "Put your secret key here";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo '<h2>You are spammer ! Get the #$%K out</h2>';
} else {
// Send the email. In your case, you can wrap pretty all of your preprocessor in this.
}

Related

How to reset Password Using PHP Codeigniter

Am working on a Password reset system whereby the user who forgot his password can request for password reset link by submitting his email used in registration. I successfully create the email, it sent the link and I test the link by clicking on it. The link went through and load the reset page but my problem is how to make the system recognise the user who click through and get all the details including Name, Token, email with which the system will confirm that the user is the user who requested the link.
The following is what I have done so far:
Controller
public function preset(){
$data['success']='';
$data['error']='';
include_once ('query/user_query.php');
$this->form_validation->set_rules('email','Email','trim|required|valid_email');
$this->form_validation->set_error_delimiters("<div class='alert alert-warning'><span type='button' class='close' data-dismiss='alert'>&times</span>","</div>");
if($this->form_validation->run() == false){
$this->load->view('passwordrecovery.php', $data);
}
else{
$eMail = $this->input->post('email');
$this->db->where("email = '$eMail'");
$this->db->from("useraccount");
$countResult = $this->db->count_all_results();
if($countResult >=1){
// $data['firstName'] = '';
// $data['lastName'] = '';
$this->db->where("email = '$eMail'");
$getUserData =$this->db->get("useraccount")->result();
foreach($getUserData as $userD){
$data['firstName'] = $userD->firstname;
$data['lastName'] = $userD->lastname;
}
$sender_email = 'xxx#gmail.com';
$user_password = 'xxxxxx';
$token = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 50);
$subject = 'Password Reset';
$message = '';
$message .= "<h2>You are receiving this message in response to your request for password reset</h2>"
. "<p>Follow this link to reset your password <a href='".site_url()."/authenticate/resetpassword/.$token' >Reset Password</a> </p>"
. "<p>If You did not make this request kindly ignore!</p>"
. "<P class='pj'><h2>Kind Regard: Votemate</h2></p>"
. "<style>"
. ".pj{"
. "color:green;"
. "}"
. "</style>"
. "";
// Configure email library
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.googlemail.com';
$config['smtp_port'] = 465;
$config['smtp_user'] = $sender_email;
$config['smtp_pass'] = $user_password;
$config['mailtype'] = 'html';
// Load email library and passing configured values to email library
$this->load->library('email', $config);
//$this->email->set_newline("rn");
$this->email->set_mailtype("html");
// Sender email address
$this->email->from($sender_email);
// Receiver email address
$this->email->to($eMail);
// Subject of email
$this->email->subject($subject);
// Message in email
$this->email->message($message);
if ($this->email->send()) {
$eMail = $this->input->post('email');
$ipadd = $this->input->ip_address();
$insert = array(
'email' => $eMail,
'ipaddress' => $ipadd,
'token' => $token
);
$this->db->insert('passwordreset', $insert);
$mail = $this->session->set_userdata('email');
$data['success'] = 'Email Successfully Send !';
$this->load->view('linksent.php', $data);
} else {
$data['error'] = '<p class="error_msg">Invalid Gmail Account or Password !
</p>';
}
$this->load->view('passwordrecovery.php', $data);
}
if($countResult <= 0){
//user already registered
$data['error'] = "<div class='alert alert-warning'> Invalid
email address<span type='button' class='close' data-
dismiss='alert'>&times</span></div>";
$this->load->view('passwordrecovery.php',$data);
}
}
}
View
<div>
<h1>Password Recovery</h1>
<h3>Enter your email to receive the password reset link in
your Inbox</h3>
<br/>
<?php echo form_open('authenticate/preset');?>
<?php echo $error;?>
<div class="form-group">
<input type="text" name="email" required="required">
</div>
<div class="form-group">
<input type="submit" value="Send" class="btn-success
btn" >
</div>
<?php echo form_close()?>
<br/><br/><br/>
</div>
Database: The following is database where I store the info:
CREATE TABLE `passwordreset` (
`resetid` int(11) NOT NULL,
`email` varchar(150) NOT NULL,
`ipaddress` varchar(25) NOT NULL,
`token` varchar(512) NOT NULL
) ENGINE
The help I need is how to get the details (Name, email, token) of the user who click the link from his email and use it to validate and also use it to update his password. Thanks
pass user email or token in url or in hidden field when user click on verify link and check in controller method.
<a href="<?=site_url('user_verification?user_email=' . $user_email . '&user_code=' . $user_code);?> Click To Verifiy Email </a>
user_verification controller
public function user_verification_get()
{
$user_email = $this->input->get('user_email');
$user_code = $this->input->get('user_code');
$data=$this->admin_model->user_verification($user_email,$user_code);
if($data)
{
$data['message'] = 'Success.';
}
else
{
$data['message'] = 'Not Valid User.';
}
$this->load->template('verify', $data);
}
Model
public function user_verification($user_email,$user_code){
$this->db->select('user_email');
$this->db->where('user_email',$user_email);
$this->db->where('user_code',$user_code);
$query = $this->db->get('users');
if($query->row_array() > 0)
{
$data['user_isactive'] = true;
$this->db->where('user_email',$user_email);
$this->db->update('users',$data);
return $query->row_array();
}
return false;
}
You have to create a database table to store the tokens. Before sending the email, You must generate a unique token and add it into a separate table. The password reset link must contain encoded token and userID. Once the password reset link is clicked, you must check the encoded token and UserID in the link matches to the entry in database? If yes, then show the change password page, If not, you must show a message "Link is expired" or whatever.
Here is the hint of code from my project.
$act_code = md5(rand(0,1000).'uniquefrasehere');
$activate['UserID'] $USERID;
$activate['TokenNumber'] = $act_code;
$activate['UserEmail'] = $email;
$activate['TokenTime'] = time();
$str_tmp = $this->db->insert_string('forgetpasswordtoken', $activate);
$query_tmp = $this->db->query($str_tmp);
Once the link is clicked, You must check using the following code:
$record = $this->user_model->checkforgot($uid[0], base64_decode($uid[1]));
if($record == true){
$data['uid'] = $uid[1];
}
else
{
$msg = "You have already changed your password or your link was expired.!";
}
And What the checkforgotpassword function does? Here is below:
function checkforgot($token, $id)
{
$qry = $this->db->query("SELECT * FROM forgetpasswordtoken WHERE TokenNumber = '".$token."' AND UserID = $id");
$num_row = $qry->num_rows();
if($num_row!=0)
{
$del = $this->db->delete('forgetpasswordtoken', array('TokenNumber' => $token, 'UserID' => $id));
return true;
}
else
{
return false;
}
}
You can further add the time limit of few hours before the link expires.
Let me know after adding this in your project.
Thanks,

ReCaptcha For Newbies

I've got ReCaptcha working but despite reading the documentation and the answers posted here, I'm still at a loss for setting up the server side. My HTML form calls <form id="contactForm" class="well" method="POST" action="php/contactform.php">.
What and where do I place the server-side recaptcha in this file? (I meant it when I titled this newbie. I really need explicit instructions):
<?php
if($_POST){
// response hash
$response = array('message'=>'');
}
try {
// Get values from form
$name=$_POST['cname'];
$email=$_POST['cemail'];
$subject=$_POST['csubject'];
$message=$_POST['cmessage'];
$formcontent="From: $name \n Email: $email \n Subject: $subject \n: $message";
$recipient = "rabbidubrow#fivegates.org";
$subject = "KHF Contact Form";
$mailheader = "From: $email \r\n";
$send_contact=mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
// let's assume everything is ok, setup successful response
$response['type'] = 'success';
$response['message'] = 'Thank you! We will be in touch shortly.';
} catch(Exception $e){
$response['type'] = 'error';
$response['message'] = $e->getMessage();
}
// now we are ready to turn this hash into JSON
print json_encode($response);
exit;
?>
You will need
1. Include your recaptcha.php
2. Declare your private and public keys
3. Check for POST of your captcha. If it success, give a response, if it fails, catch the exception.
Below is one of my scripts that was done up for your reference.
require_once('assets/config/recaptchalib.php');
$publickey = "xxxx";
$privatekey = "xxxxx";
if ($_POST["recaptcha_response_field"]) {
$resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
if ($resp->is_valid) {
$continue = true;
}
}

Redirect link page is preventing my email from sending

I added this in email signature:
Test Website
testwebsite.com
==========
If you click testwebsite.com, it will redirect to my website mywebsite.com
Whenever I used testwebsite.com as part of the email signature on my site, the email notification is not sending. But if I changed that to mywebsite.com, the email notification is working fine.
==========
By the way, my email notification was integrated on mywebsite.com using SendMail in CodeIgniter framework.
Could you please help me why my marketing domain testwebsite.com is preventing the email notifications from sending successfully.
PS. I just used test website URLs in the above scenario for security purposes.
======
function send_email_template($template, $recipient, $subject = null, $vars = null) {
$ci = & get_instance();
$ci->load->model('default/m_settings');
//get site data
$website = $ci->M_website->getWebsite();
$ci->load->library('email');
$ci->email->clear();
$config['mailtype'] = 'html';
$ci->email->initialize($config);
// Set default subject.
if ($subject == null) {
// Try to find a "_subject" setting for the template specified.
$subject = $ci->m_settings->get($template . '_subject');
if ($subject) {
$subject = $subject->setting_value;
} else {
$subject = '';
}
}
$template = $ci->m_settings->get($template);
$body = htmlspecialchars_decode(cs_parse_vars($template->setting_value, $vars));
$body .= $ci->m_settings->get('global_email_footer')->setting_value;
$ci->email->set_newline("\r\n");
//get admin email
$ci->load->model('admin/M_administrator');
$admin_email = $ci->m_settings->get('admin_outgoing_email')->setting_value;
$email_sender_from = ($admin_email) ? $admin_email : 'no-reply#' . strtolower(preg_replace('/\s/', '-', $website['name']));
$ci->email->from($email_sender_from, $website['name']);
// _APPLICATION_ENV_ is set in /index.php
if (_APPLICATION_ENV_ != 'PRODUCTION') {
$recipient = _EMAIL_RECEPIENT_;
}
if ($recipient == '') {
#$recipient = 'jamygallardo#gmail.com';
}
$ci->email->to($recipient);
$ci->email->subject('[' . $website["name"] . '] ' . $subject);
$ci->email->message($body);
if ($ci->email->send()) {
return TRUE;
} else {
show_error('mailer error:' . $ci->email->print_debugger());
}
return TRUE;
}
Thanks,
Jamaica

Can't send email via codeinginter using cpanel email account

I have problem when sending email from my server to somebody account
i mean that i need to send email from
myemail#mydomain.com to any another account Whether Live, hotmail or gmail etc.
of course that from PHP script
I have been created email account from my CPanel, and i tried to send email by this code.
$config['protocol'] = 'smtp';
$config['smtp_host'] = "mail.mydomain.com";
$config['smtp_user'] = "myemail#mydomain.com";
$config['smtp_pass'] = "password";
$config['smtp_port'] = "25";
$this->load->library('email',$config);
$this->email->from("myemail#mydomain.com", 'test');
$this->email->to("actualemail#live.com"); // the user email
$this->email->subject("hello");
$this->email->message("test test test");
if (!$this->email->send()) {
echo "error";
//$this->email->print_debugger();
exit;
}
//$this->email->print_debugger();
//exit;
echo "success";
Note that i'm using codeigniter framework.
The strange is there is no any problem in sending email , i get success message, but when i go to my receive email account i not found
any email. what to do, I'm boring form a lot of attempts :( .
try this:
$to = 'you#gmail.com';
$subject = 'my subject';
$msg = 'Hi..........';
$headers = "From: info#domain.com\r\nReply-To: info#domain.com";
$mail_sent = #mail( $to, $subject, $msg, $headers );
echo $mail_sent ? "Mail sent" : "Mail failed";
It directly takes details from your server & sends mail.
This works fine on my site.

JMail usage for cutsom component programming

My code works when the format is html.
<pre>
public function partOrder()
{
$input=JFactory::getApplication()->input;
$mailer =JFactory::getMailer();
$config =JFactory::getConfig();
$mailer->setSender(array("email#email.com","name"));
$mailer->addRecipient("somerecipient#somerecipent.com");
$body="Some html message";
$mailer->isHTML(true);
$mailer->Encoding = 'base64';
$mailer->setBody($body);
$send =$mailer->Send();
$respond="";
if ( $send !== true ) {
$respond= 'Error sending email: ' . $send->message;
} else {
$respond= 'Mail sent';
}
echo $respond;
}
</pre>
When I use same function on controller for json format I get the "Mail Sent" message. But Mail doesn't reach to recipient;
I don't think there's anything wrong with your function.
However, I noticed that Gmail is quite picky when it comes which emails come trough to inbox:
All Global Configuration > Server > Mail Settings must be filled in and valid.
These settings have to be used for JMail configuration
// Initialize some variables
$app = JFactory::getApplication();
$mailer = JFactory::getMailer();
// Get mailer configuration
$mailfrom = $app->getCfg('mailfrom');
$fromname = $app->getCfg('fromname');
$sitename = $app->getCfg('sitename');
// Clean the email data
$contact_to = JMailHelper::cleanAddress( $data['contact_to'] );
$subject = JMailHelper::cleanSubject( $data['contact_subject'] );
$body = JMailHelper::cleanBody( $data['contact_message'] );
$reply_to_email = JMailHelper::cleanAddress( $data['contact_reply_to'] );
$reply_to_name = JMailHelper::cleanLine( $data['contact_reply_to_name'] );
// Construct mailer
$mailer
->addRecipient($contact_to)
->addReplyTo(array($reply_to_email, $reply_to_name))
->setSender(array($mailfrom, $fromname))
->setSubject($sitename . ': ' . $subject)
->setBody($body)
;
// Send email
$sent = $mailer->Send();

Resources