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;
}
}
Related
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'>×</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'>×</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,
I am using this below code to login and redirect to account page:
<?php
include('store/app/Mage.php');
Mage::app();
if($_POST && $_POST['login']['username'] && $_POST['login']['password']){
$email = $_POST['login']['username'];
$password = $_POST['login']['password'];
$session = Mage::getSingleton('customer/session');
try {
$log = $session->login($email, $password);
$session->setCustomerAsLoggedIn($session->getCustomer());
$customer_id = $session->getCustomerId();
$send_data["success"] = true;
$send_data["message"] = "Login Success";
$send_data["customer_id"] = $customer_id;
Mage::getSingleton('customer/session')->loginById($customer_id);
Mage_Core_Model_Session_Abstract_Varien::start();
}catch (Exception $ex) {
$send_data["success"] = false;
$send_data["message"] = $ex->getMessage();
}
}else {
$send_data["success"]=false;
$send_data["message"]="Enter both Email and Password";
}
echo json_encode($send_data);
?>
And then on file from where I am making ajax request, I am using this code:
if(data.success){
window.location = "http://domain.com/store/customer/account/"
}
But it always show user as logout, though I do get correct customer id as well as success.
$email = strip_tags($_GET["login"]);
$password = strip_tags($_GET["psw"]);
function loginUser( $email, $password ) {
umask(0);
ob_start();
session_start();
Mage::app('default');
Mage::getSingleton("core/session", array("name" => "frontend"));
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId;
$customer->setStore($store);
try {
$customer->loadByEmail($email);
$session = Mage::getSingleton('customer/session')->setCustomerAsLoggedIn($customer);
if($session->login($email, $password)){ return true;} else { };
}catch(Exception $e){
return $e->getMessage();
}
}
if (loginUser($email,$password) == 1) {
echo ".. user loged as ".Mage::getSingleton('customer/session')->getCustomer()->getName()."<br>";} else {
//bad things goes here
}
In my case Martin's code works if I change the session name
session_name('frontend');
session_start();
If you leave the session name alone it defaults PHPSESSID which isn't the same as that created by Magento on a manual login and didn't work in my install. That may vary, try logging in manually and check your cookie names.
session_name documentation: http://php.net/manual/en/function.session-name.php
i am developing an application where i need some suggestions. Here is the detail of the problem.
public function form()
{
$this->load->helper('inflector');
$id = $this->uri->segment(3,0);
if($data = $this->input->post()){
$result = $this->form_validation->run();
if($result){
if($id > 0){
// here update code
}else{
$this->mymodel->insert($data);
$this->session->set_flashdata('message','The page has been added successfully.');
$this->redirect = "mycontroller/index";
$this->view = FALSE;
}
}else{
//$this->call_post($data);
$this->session->set_flashdata('message','The Red fields are required');
$this->view = FALSE;
$this->redirect = "mycontroller/form/$id";
}
}else{
$row = $this->mymodel->fetch_row($id);
$this->data[]= $row;
}
}
public function _remap($method, $parameters)
{
if (method_exists($this, $method))
{
$return = call_user_func_array(array($this, $method),$parameters);
}else{
show_404();
}
if(strlen($this->view) > 0)
{
$this->template->build('default',array());
}else{
redirect($this->redirect);
}
}
Here you can see how i am trying to reload the page on failed validation.
Now the problem is that i have to display the flash data on the view form which is only available after redirect and i need to display the validation errors to which are not being displayed on redirect due to the loss of post variable. If i dont use redirect then cant display flashdata but only validation errors. I want both of the functionalities togather. I have tried even creating POSt again like this
public function call_post($data)
{
foreach($data as $key => $row){
$_POST[$key] = $row;
}
}
Which i commented out in the formmethod.How can i achieve this.
Here's a thought.
I think you can add the validation error messages into the flash data. Something like this should work:
$this->session->set_flashdata('validation_error_messages',validation_errors());
Notice the call to the validation_errors function. This is a bit unconventional, but I think it should work. Just make sure that the code are executed after the statement $this->form_validation->run(); to make sure the validation error messages are produced by the Form Validation library.
well i have little different approach hope will help you here it is
mycontroller extend CI_Controller{
function _remap($method,$params){
switch($method){
case 'form':
$this->form($params);
break;
default:
$this->index();
break;
}
}
function form(){
$this->load->helper('inflector');
$id = $this->uri->segment(3,0);
$this->form_validation->set_rules('name','Named','required|trim');
$this->form_validation->set_rules('email','email','required|valid_email|trim');
// if validation fails and also for first time form called
if(!$this->form_validation->run()){
$this->template->build('default',array());
}
else{ // validation passed
$this->save($id)
}
}
function save($id = 0){
$data = $this->input->post();
if($id == 0){
$this->mymodel->insert($data);
$this->session->set_flashdata('message','The page has been added successfully.');
$this->redirect = "mycontroller/index";
$this->view = FALSE;
}else{
// update the field
$this->session->set_flashdata('message','The Red fields are required');
}
redirect("mycontroller/index");
}
}
your form/default view should be like this
<?
if(validation_errors())
echo validation_errors();
elseif($this->session->flashdata('message'))
echo $this->session->flashdata('message');
echo form_open(uri_string());// post data to same url
echo form_input('name',set_value('name'));
echo form_input('email',set_value('email'));
echo form_submit('submit');
echo form_close();
try it if you face any problem post here.
How to send email in magento writing an action in index controller?
my index controller;
public function postAction()
{
$post = $this->getRequest()->getPost();
if(!$post) exit;
$translate = Mage::getSingleton('core/translate');
$translate->setTranslateInline(false);
try {
$postObject = new Varien_Object();
$postObject->setData($post);
if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
echo '<div class="error-msg">'.Mage::helper('contacts')->__('Please enter a valid email address. For example johndoe#domain.com.').'</div>';
exit;
}
$storeId = Mage::app()->getStore()->getStoreId();
$emailId = Mage::getStoreConfig(self::XML_PATH_SAMPLE_EMAIL_TEMPLATE);
$mailTemplate = Mage::getModel('core/email_template');
$mailTemplate->setDesignConfig(array('area'=>'frontend', 'store'=>$storeId))
->setReplyTo($post['email'])
->sendTransactional($templateId, $sender, $email, $name, $vars=array(), $storeId=null)
if (!$mailTemplate->getSentSuccess()) {
echo '<div class="error-msg">'.Mage::helper('contacts')->__('Unable to submit your request. Please, try again later.').'</div>';
exit;
}
$translate->setTranslateInline(true);
echo '<div class="success-msg">'.Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.').'</div>';
}
catch (Exception $e) {
$translate->setTranslateInline(true);
echo '<div class="error-msg">'.Mage::helper('contacts')->__('Unable to submit your request. Please, try again later.').$e.'</div>';
exit;
}
}
is there any wrong..
please help me to out of this..
Thanks in advance..
Here's another way, if you don't need templates.
Call from a controller.
<?php
$body = "Hi there, here is some plaintext body content";
$mail = Mage::getModel('core/email');
$mail->setToName('John Customer');
$mail->setToEmail('customer#email.com');
$mail->setBody($body);
$mail->setSubject('The Subject');
$mail->setFromEmail('yourstore#url.com');
$mail->setFromName("Your Name");
$mail->setType('text');// You can use 'html' or 'text'
try {
$mail->send();
Mage::getSingleton('core/session')->addSuccess('Your request has been sent');
$this->_redirect('');
}
catch (Exception $e) {
Mage::getSingleton('core/session')->addError('Unable to send.');
$this->_redirect('');
}
It looks like there are a few problems with the way you are calling sendTransactional(). First off, $templateId is not defined, it looks like you've actually stored the template id in $emailId. Also, $sender, $email, and $name are undefined. You can try something like this:
->sendTransactional($emailId, 'general', $post['email'], "Need a send to name here")
This is only going to work if you are getting a valid template id back from your call to getStoreConfig(). You'll also need to set the last name param correctly.
There could be other issues, but that's what I noticed with a quick glance anyway.
Finally i created a function for sending mail by using zend
public function sendMail()
{
$post = $this->getRequest()->getPost();
if ($post){
$random=rand(1234,2343);
$to_email = $this->getRequest()->getParam("email");
$to_name = 'Hello User';
$subject = ' Test Mail- CS';
$Body="Test Mail Code : ";
$sender_email = "sender#sender.com";
$sender_name = "sender name";
$mail = new Zend_Mail(); //class for mail
$mail->setBodyHtml($Body); //for sending message containing html code
$mail->setFrom($sender_email, $sender_name);
$mail->addTo($to_email, $to_name);
//$mail->addCc($cc, $ccname); //can set cc
//$mail->addBCc($bcc, $bccname); //can set bcc
$mail->setSubject($subject);
$msg ='';
try {
if($mail->send())
{
$msg = true;
}
}
catch(Exception $ex) {
$msg = false;
//die("Error sending mail to $to,$error_msg");
}
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($msg));
}
}
I'm fairly new to php and I'm using a script that creates a function called the "mime_mailer" which essentially allows me to use PHP to send emails that are able to be designed with CSS instead of being merely plain text.
Yet, in my registration script, I try to write some code that sends a CSS email, but I get an error saying that there's a syntax error. Could someone please fill me in on this?
$subject = "Your Red-line Account";
$css = "body{ color: #090127; background-color: #f0f0f0; }";
$to = $usercheck;
//Message
$message =<<<END
<html>
<head>
<title>
Red-line
</title>
</head>
<body>
<p>
Hi $first_name,
</p>
<p>
Your Red-line account is almost complete. To finish, go to <a href='www.thered-line.com'>The Red-line</a> and enter your eight digit confirmation code.
</p>
<p>
Your confirmation code is: <b>$code</b>
</p>
<p>
Sincerely,
</p> <br />
<p>
The Red-line Operator
</p>
</body>
</html>
END;
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= "From: The Red-line <messages#theredline.com>\r\n";
$headers .= "To: $first_name $last_name <$usercheck>\r\n";
// Mail it
require_once("function_mime_mailer.php");
mime_mailer($to, $subject, $message, $headers, NULL, $css);
}
Here is the code for the "function_mime_mailer.php" file.
if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])) send_404(); // stop http access to this file
function mime_mailer($to, $subject, $message, $headers = NULL, $attachments = NULL, $css = NULL)
{
if(!preg_match('/^([_a-z0-9-]+)(\.[_a-z0-9-]+)*#([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a- z]{2,6})$/', $to)) return FALSE;
if(preg_match('/<(html|head|body|div|a|h|p|table|br|img|b|hr|ol|ul|span|pre|i|form)[^>]*[^>]*>/i', $message)) $html = TRUE;
if(stristr($message, '<body')) $message = stristr($message, '<body');
$message = delete_local_links($message);
if(empty($headers)){
$headers = "MIME-Version: 1.0\n";
}else{
$headers.= "\nMIME-Version: 1.0\n";
}
if(empty($html)){
$result = plain_text($message);
}elseif(isset($html) and $html == TRUE){
if(!isset($css)) $css = NULL;
if(preg_match('/<img[^>]+>/i', $message)){
$result = multipart_related($message, $css);
}else{
$result = multipart_alternative($message, $css);
}
}
$result['message'] = delete_non_cid_images($result['message']);
if(!empty($attachments)){
$parts = attachments($attachments);
array_unshift($parts, implode('', $result));
$result = multipart_mixed($parts);
}
$headers = $headers.$result['headers'];
//print '<pre>'.htmlspecialchars($headers.$result['message']).'</pre>';exit;
if(mail($to, $subject, $result['message'], $headers)) return TRUE;
return FALSE;
}
?>
Just had the same problem.
Turned out to be content on the same line as my opening HERDEOC
wrong example
echo <<<HEREDOC code started on this line
HEREDOC;
correct example
echo <<<HEREDOC
code should have started on this line
HEREDOC;
Hope this helps someone else!
Have a look at the List of Parser tokens.
T_SL references to <<.
You should not use tabs or spaces before you use END;. Have a look at this huge warning.
A side note, but might well help someone: a bad git merge can cause this. Consider:
function foo
<<<<<<< HEAD
$bar = 1;
<<<<<<< e0f2213bc34d43ef
$bar = 2;
The PHP parser would produce the same error.
Source: just got bit by this ;)
It had the same exact same issue but mine was because I had whitespace at the end of my heredoc on the top line:
$var = <<< HTML(whitespaces here caused the error)
stuff in here
HTML;
Source: http://realtechtalk.com/_syntax_error_unexpected_T_SL_in_PHP_Solution-2109-articles
What version of php are you using?
The nowdoc syntax is only valid since PHP 5.3.0.
See the manual:
http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc
There is a bug in function_mime_mailer.php:
if(empty($headers)){
$headers = "MIME-Version: 1.0\n";
}else{
$headers.= "\nMIME-Version: 1.0\n";
}
should be
if(empty($headers)){
$headers = "MIME-Version: 1.0\r\n";
}else{
$headers.= "\r\nMIME-Version: 1.0\r\n";
}
also, if you include the MIME-Version header, then the function will include it once more - effectively having two of them.
Problem is related to needless spaces/tabs in code...
Ran into this after using get merge feature/branchname. We use Prettier as formatter, so after accepting both changes - saving the file, fixed the problem.