Probably something simple, but heres my problem, I have implememnted a simple captcha into my user system, but I can't seem to use the callback form validation to check to see if the captcha is correct.
I store the answer in the users session, and on form validation I check if it is correct.
You can see it live here: http://77.96.119.180/beer/user/register
Please excuse any references to beer ;)
Here is my code:
$this->form_validation->set_rules('captcha', 'Image verification', 'trim|required|xss_clean|integer|callback_captcha_check');
Here is part of the form
// CAPTCHA
$random_word = rand(10000, 99999);
$vals = array(
'word' => $random_word,
'img_path' => './captcha/',
'img_url' => 'http://77.96.119.180/beer/captcha/',
'font_path' => './captcha/fonts/pdark.ttf',
'img_width' => '150',
'img_height' => 50,
'expiration' => 7200
);
$cap = create_captcha($vals);
// Store captcha answer in session
$this->session->set_userdata('captcha_answer', $random_word);
$content .= form_label('Please enter the numbers in the box to verify you are human (Hint: Only numbers will appear)', 'captcha');
$content .= '<div class="left" style="margin-left:20px;">' . $cap['image'] . '</div>';
$content .= form_input(array('name' => 'captcha', 'value' => '', 'class' => 'right', 'style' => 'width:75%; margin-top:5px;'));
And here is the callback function
public function captcha_check($str)
{
if ($str == $this->session->userdata('captcha_answer'))
{
// Captcha is correct
$this->form_validation->set_message('captcha', 'The %s was wrong, please try again');
return FALSE;
}
else
{
return TRUE;
}
}
your validation rules are reversed in your callback function. your return true and return false logic needs to be reversed.
just change your if statement to this:
if ($str != $this->session->userdata('captcha_answer'))
Related
I'm a newbie in web development (or development) and I'm using Laravel (if it matters somehow). I have a reCAPTCHA in my form. It works, but now I have to verify user's keyword in recaptcha.
Documentation: https://developers.google.com/recaptcha/docs/verify sounds simple, but somehow I can't write the code lines for verification. I was looking for some examples, but they're not for Laravel but for pure PHP, and I didn't see where is the 'https://www.google.com/recaptcha/api/siteverify?secret=your_secret&response=response_string&remoteip=user_ip_address' URL used in the examples.
My controller is:
public function postMessage() {
require_once('recaptchalib.php');
$privatekey = "MY_PRIVATE_KEY";
?????
// this should be executed only after validation
DB::table('messages')->insert(['name' => Input::get('name'),
'email' => Input::get('email'),
'message' => Input::get('message'),
'datetime' => \Carbon\Carbon::now()->toDateTimeString()]);
So please, instruct me, how could i get JSON object with response, or what should I write instead of ?????
Well, at the end I was able to find solution by myself:
public function postMessage() {
$secret = '7LdL3_4SBAAAAKe5iE-RWUya-nD6ZT7_NnsjjOzc';
$response = Input::get('g-recaptcha-response');
$url = 'https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$response;
$jsonObj = file_get_contents($url);
$json = json_decode($jsonObj, true);
if ($json['success']==true) {
DB::table('messages')->insert(['name' => Input::get('name'),
'email' => Input::get('email'),
'message' => Input::get('message'),
'datetime' => \Carbon\Carbon::now()->toDateTimeString()]);
return Redirect::route('contact')->with('okmessage', 'Ďakujeme. Vaša správa bola odoslaná');
} else {
return Redirect::route('contact')->with('errormessage', 'Chyba! Zaškrtnite "Nie som robot" a zadajte správny kód.');
}
}
I am trying to get a response from MailChimp to return a message to the Subscriber. The subscribtion is working fine but I do not get any response from MailChimp. I am a Noob at PHP so do I neeed to use JSON or can it be done like in my Code with PHP?
$MailChimp = new \drewm\MailChimp('12122338484487841-us1');
$result = $MailChimp->call('lists/subscribe', array(
'id' => '1123334444',
'email' => array('email'=>$check_mail['customers_email_address']),
'merge_vars' => array('FNAME'=>$check_mail['customers_firstname'], 'LNAME'=>$check_mail['customers_lastname']),
'double_optin' => true,
'update_existing' => false,
'replace_interests' => false,
'send_welcome' => true,
));
// CHECK MAILCHIMP IF EMAIL EXIST
if( $result === false ) {
return 'You have already subscribed to the List';
}
else if( isset($result->status) && $result->status == 'error' ) {
// Error info: $result->status, $result->code, $result->name, $result->error
}
// CHECK MAILCHIMP IF EMAIL EXIST
Thanks
Cool , then you can check like..
if( $result['name'] === 'List_AlreadySubscribed' ) {
return $result['error'];// which returns "mail#example.com is already subscribed to list SyncTest. Click here to update your profile." as a string.
}
I'm trying to add feature to our corporate website (this module called 'userpasswords2' searches database of local mailsystem passwords). I'm using AJAX autocomplete and modification of the form.
I cannot submit the form by enter key. AJAX autocomplete works fine, but when I choose the user, the form can only be submitted by submit button.
I would like it to work like here https://api.drupal.org/api/drupal - user enters for example 'hook', chooses for example hook_menu, hits enter, then hits enter again and get the result!
So again - clicking submit button works fine, hitting 'enter' key doesn't work.
Googled a lot, the workarounds I've found doesn't work for me. Please help.
function userpasswords2_menu() {
$items = array();
$items['userpasswords2'] = array(
'title' => 'User passwords',
'page callback' => 'drupal_get_form',
'page arguments' => array('userpasswords2_form'),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
$items['userpasswords2/ajax_username_autocomplete_callback2'] = array(
'page callback' => 'ajax_username_autocomplete_callback2',
'type' => MENU_CALLBACK,
'access callback' => TRUE,
);
return $items;
}
function userpasswords2_form($form, &$form_state) {
$form = array();
$form['user'] = array(
'#type' => 'textfield',
'#title' => t('Enter username'),
'#autocomplete_path' => 'userpasswords2/ajax_username_autocomplete_callback2',
'#executes_submit_callback' => 'TRUE',
);
$form['box'] = array(
'#type' => 'markup',
'#prefix' => '<div id="box">',
'#suffix' => '</div>',
'#markup' => '<br>',
);
$form['actions']['submit'] = array(
'#type' => 'submit',
'#ajax' => array(
'callback' => 'userpasswords2_callback',
'wrapper' => 'box',
),
'#value' => t('Submit'),
);
return $form;
}
function ajax_username_autocomplete_callback2($string = "") {
$matches = array();
if ($string) {
$result = db_select('my_domain_passwords')
->fields('my_domain_passwords',array('fullname','password'))
->condition('fullname', db_like($string) . '%', 'LIKE')
->range(0,10)
->execute();
foreach ($result as $user) {
$form['custom']['username'] = $matches[$user->fullname] = check_plain($user->fullname);
$form['custom']['password'] = check_plain($user->password);
}
}
drupal_json_output($matches);
}
function userpasswords2_form_validate($form, &$form_state) {
$username = $form_state['values']['user'];
$matches = array();
// select from database by fullname
$result = db_select('my_domain_passwords')
->fields('my_domain_passwords', array('fullname'))
->condition('fullname', db_like($username), 'LIKE')
->range(0,1)
->execute()
->fetchField();
if (!empty($username)) {
$form_state['custom']['username'] = $result;
$password = db_select('my_domain_passwords')
->fields('my_domain_passwords', array('password'))
->condition('fullname', db_like($username), 'LIKE')
->range(0,1)
->execute()
->fetchField();
$form_state['custom']['password'] = $password;
}
return $form;
}
function userpasswords2_callback($form, &$form_state) {
if ( (!empty($form_state['custom']['username'])) && (!empty($form_state['custom']['password'])) ) {
$output_string = $form_state['custom']['username'] . " : " . $form_state['custom']['password'];
} else {
$output_string = "No such user: " . $form_state['values']['user'];
}
$username = $form_state['custom']['username'];
$password = $form_state['custom']['password'];
$element = $form['box'];
$element['#markup'] = $output_string;
return $element;
}
If you remove your autocomplete, you can be able to submit by press enter. So the issue is in the autocomplete function. You need to patch the misc/autocomplte.js. Following is the patch, check out the link for more details.
case 13: // Enter.
case 27: // Esc.
this.hidePopup(e.keyCode);
if (e.keyCode == 13 && $(input).hasClass('auto_submit')) {
input.form.submit();
}
This could be help you https://www.drupal.org/project/drupal/issues/309088
I am using fancy box iframe to display my page which has the file upload button. when i click form submit i got the "File exceeds the defined ini size". i checked some of links under google and stackoverflow. But not able to find. I have enctype="multipart/form-data" in my form. Following is my code
public function createForm($data = array())
{
$this->setMethod(Zend_Form::METHOD_POST);
$this->setEncType(Zend_Form::ENCTYPE_MULTIPART);
$this->setAttrib('id', 'createsub');
$this->setAction(
$this->getView()->getHelper('url')->url(array(
'controller' => 'test',
'action' => 'create'
))
);
$this->setDecorators(array(
'Description',
'FormElements',
'Form'
));
$fnameNotEmpty = new Zend_Validate_NotEmpty();
$fnameNotEmpty->setMessage('Name cannot be empty.');
$fnameStrlen = new Zend_Validate_StringLength(1, 20);
$name = new Zend_Form_Element_Text('name', array(
'label' => 'Name:',
'value' => '',
'class' => 'text-size text',
'tabindex' => '1',
'required' => true,
'validators' => array(
array($fnameNotEmpty, true),
array($fnameStrlen, true)
),
'decorators' => $this->requiredElementDecorators,
'description' => '<img src="../../'.$baseurl.'/images/star.png" alt="required" />',
'filters' => array('StringTrim')
));
$this->addElement($name);
.... ..... .....
$brochure = new Zend_Form_Element_File('brochure', array(
'label' => 'Brochure:*',
'value' => '',
'class' => 'text-size text',
'tabindex' => '3',
'required' => true,
'filters' => array('StringTrim')
));
$this->addElement($brochure);
$submit = $this->createElement('button','addtbtn',array('class'=>'Test','label'=>'Create'));
$submit->setIgnore(true);
$this->addElement($submit);
return $this;
}
Also if i did not use iframe, I can able to upload my image...Very Strange.
I make the validation using Ajax by following code ,
<script type="text/javascript">
var Path="<?php echo $this->eurl; ?>"
$(function()
{
vReg=0
$("#addtbtn").click(function()
{
if(vReg == 1)
{
return true;
}
else{
var url = 'validateform';
var data = {};
$("input").each(function()
{
data[$(this).attr('name')] = $(this).val();
});
$("select").each(function()
{
data[$(this).attr('name')] = $(this).val();
});
$("textarea").each(function()
{
data[$(this).attr('name')] = $(this).val();
});
$.post(url,data,function(resp)
{
vError=""
for(id in resp){
oResp=resp[id];
for(key in oResp){
vError +=oResp[key]+"\n"
}
}
if(vError == ''){
vReg=1
$("#createform").attr('target','_top');
$("#createform").submit();
return true;
}
else{
$("#createform").attr('target','_self');
alert(vError)
return false;
}
},'json');
}
});
});
</script>
Also Has the following function in my controller
public function validateformAction()
{
$this->_helper->viewRenderer->setNoRender();
$this->_helper->getHelper('layout')->disableLayout();
$p = new Admin_Model_DbTable_Test();
$p = $p->getData();
foreach($p AS $k => $v)
{
$p[$v['catid']] = $v['name'];
}
$form = new Admin_Model_Form_SubTest();
$f = $form->createForm(array('parents' => $p));
$f->isValid($this->_getAllParams());
$json = $f->getMessages();
echo Zend_Json::encode($json);
}
So this will call the function which i gave on the top of the post and do the validation and return the error.But here i always getting "File exceeds the defined ini size " What I done wrong this code.
Kindly help me on this.
Check the upload_max_filesize setting in your .ini file(s). That's where this error comes from.
When you call .val() on your file input, you get the path of the file you have selected, while your validator will be expecting the file itself, hence the strange error. Most people opt to skip file inputs when doing ajax validation, and just check it on submit.
I downloaded the sample code to request a rate from fedex's website... i placed the WSDL file in the proper location, I have my acct number, password, meter number, and key. When I run the script I get this error:
Error in processing transaction.
ERROR
prof
1000
Authentication Failed
The script they give is as follows, and yes i do actually replace the XXX and YYY everywhere it says.:
<?php
// Copyright 2009, FedEx Corporation. All rights reserved.
// Version 7.0.0
require_once('fedex-common.php5');
$newline = "<br />";
//The WSDL is not included with the sample code.
//Please include and reference in $path_to_wsdl variable.
$path_to_wsdl = "RateService_v7.wsdl";
ini_set("soap.wsdl_cache_enabled", "0");
$client = new SoapClient($path_to_wsdl, array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information
$request['WebAuthenticationDetail'] = array('UserCredential' =>
array('Key' => 'XXX', 'Password' => 'YYY')); // Replace 'XXX' and 'YYY' with FedEx provided credentials
$request['ClientDetail'] = array('AccountNumber' => 'XXX', 'MeterNumber' => 'YYY');// Replace 'XXX' with your account and meter number
$request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Request v7 using PHP ***');
$request['Version'] = array('ServiceId' => 'crs', 'Major' => '7', 'Intermediate' => '0', 'Minor' => '0');
$request['ReturnTransitAndCommit'] = true;
$request['RequestedShipment']['DropoffType'] = 'REGULAR_PICKUP'; // valid values REGULAR_PICKUP, REQUEST_COURIER, ...
$request['RequestedShipment']['ShipTimestamp'] = date('c');
$request['RequestedShipment']['ServiceType'] = 'FEDEX_GROUND'; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ...
$request['RequestedShipment']['PackagingType'] = 'YOUR_PACKAGING'; // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ...
$request['RequestedShipment']['Shipper'] = array('Address' => array(
'StreetLines' => array('10 Fed Ex Pkwy'), // Origin details
'City' => 'Memphis',
'StateOrProvinceCode' => 'TN',
'PostalCode' => '38115',
'CountryCode' => 'US'));
$request['RequestedShipment']['Recipient'] = array('Address' => array (
'StreetLines' => array('13450 Farmcrest Ct'), // Destination details
'City' => 'Herndon',
'StateOrProvinceCode' => 'VA',
'PostalCode' => '20171',
'CountryCode' => 'US'));
$request['RequestedShipment']['ShippingChargesPayment'] = array('PaymentType' => 'SENDER',
'Payor' => array('AccountNumber' => 'XXX', // Replace 'XXX' with payor's account number
'CountryCode' => 'US'));
$request['RequestedShipment']['RateRequestTypes'] = 'ACCOUNT';
$request['RequestedShipment']['RateRequestTypes'] = 'LIST';
$request['RequestedShipment']['PackageCount'] = '2';
$request['RequestedShipment']['PackageDetailSpecified'] = true;
$request['RequestedShipment']['PackageDetail'] = 'INDIVIDUAL_PACKAGES'; // Or PACKAGE_SUMMARY
$request['RequestedShipment']['RequestedPackageLineItems'] = array('0' => array('Weight' => array('Value' => 2.0,
'Units' => 'LB'),
'Dimensions' => array('Length' => 10,
'Width' => 10,
'Height' => 3,
'Units' => 'IN')),
'1' => array('Weight' => array('Value' => 5.0,
'Units' => 'LB'),
'Dimensions' => array('Length' => 20,
'Width' => 20,
'Height' => 10,
'Units' => 'IN')));
try
{
$response = $client ->getRates($request);
if ($response -> HighestSeverity != 'FAILURE' && $response -> HighestSeverity != 'ERROR')
{
printRequestResponse($client);
}
else
{
echo 'Error in processing transaction.'. $newline. $newline;
foreach ($response -> Notifications as $notification)
{
if(is_array($response -> Notifications))
{
echo $notification -> Severity;
echo ': ';
echo $notification -> Message . $newline;
}
else
{
echo $notification . $newline;
}
}
}
writeToLog($client); // Write to log file
} catch (SoapFault $exception) {
printFault($exception, $client);
}
?>
I am not quite sure why it isn't working, i've read about using a proxy, but I am not quite sure how i would use it in this case? Isn't the point of using SOAP and WSDL to avoid using CURL, Direct Connect type stuff?
Agree with Aditya Kumar,
or check in your wsdl file at bottom. there is a code
<s1:address location="https://wsbeta.fedex.com:443/web-services/ship"/>
change it to
<s1:address location="https://ws.fedex.com:443/web-services/ship"/>
I Was also having the Same issue, i was entering the password which i was using to login, but we need to enter the password which will be sent your email address after registering for the test account information with FEDEX:
Please make sure the values you have entered below are correct:
if($var == 'shipaccount') Return 'Your Account Number';
if($var == 'meter') Return 'Your meter number';
if($var == 'key') Return 'Your key'; //These values wiil be shown in the page after registering for the test account
if($var == 'password') Return 'Your Password'; // This will be sent to you by Fedex to your mail this is not your account password using to login
If you use SoapUI ( http://www.soapui.org/ ) to contact the WSDL, what is the response you get?
(SoapUI enables you to test SOAP/Wsdl's without programming, so you can check if the calls are correct, if they are, then the problem is in your code.)
Edit fedex-common.php5 file replace 'XXX' with your info in the following params
if($var == 'shipaccount') Return 'YOUR TEST ACCOUNT NUMBER HERE';
if($var == 'billaccount') Return 'YOUR TEST ACCOUNT NUMBER HERE';
if($var == 'meter') Return 'YOUR TEST METER NUMBER HERE';
if($var == 'key') Return 'YOUR TEST KEY HERE';
if($var == 'password') Return 'YOUR TEST PASSWORD HERE';
Hope this helps someone.
in library file fedex-common.php5 change following fields to provided credentials:
if($var == 'shipaccount') Return '123456';
if($var == 'billaccount') Return '123456';
if($var == 'dutyaccount') Return '123456';
if($var == 'accounttovalidate') Return '123456';
if($var == 'meter') Return '654321';
if($var == 'key') Return 'ASDE324dfe';
if($var == 'password') Return 'K2wedrf4ASDE324dfe';
in wsdlfile ShipService_v*.wsdl change following thing:
<s1:address location="https://ws.fedex.com:443/web-services/ship"/>
Hope it'll work for you.
I faced this issue from earlier and found solution finally after a discussion with FedEx Technical Person.See why we are facing such error all because of Developer Test Account we generated from developer website.One thing we should keep in mind that Test Account Number start with "6" is of Production & Key Start with "5" is Correct Test Key.So Please check your Test Key when you get Authentication problem with Error Code 1000.
Another Reason apart from this is might be your Fedex Webservice endpoint is different like for ex "https://wsbeta.fedex.com/web-services/track", this is Sandbox mode url and in production environment url should be like this "https://ws.fedex.com/web-services/track". There is no "beta" mode in URL for Production,So please check endpoint.