how to integrate google reCAPTCHA in codeigniter? - codeigniter

I am working in codeigniter 2.4. I have to use google recaptcha in ony of my project.Below is my code.
// field validation
$this->form_validation->set_rules('recaptcha_challenge_field', 'Captcha Code', 'trim|required|xss_clean|callback_checkCaptcha');
The call back function is :
function checkCaptcha($captcha){
$resp = $this->recaptcha->recaptcha_check_answer ( $this->input->ip_address(), $this->input->post('recaptcha_challenge_field',true), $this->input->post('recaptcha_response_field',true));
if($resp->is_valid)
{
return true;
}
else
{
$this->form_validation->set_message('checkCaptcha', 'Sorry Invalid captcha code');
return false;
}
}
But I am getting this error:
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: controllers/offer.php
Line Number: 59
Please help me where I am going wrong .
Thanks.

I have updated my code and it works for me now. In the captcha library I have made the is_valid property public and then I replaced
if($resp->is_valid)
with
if($this->recaptcha->is_valid)
Now it works for me.
Thanks for all who responed my question.

public function captcha_verify(){
$form_response = $this->input->post('g-recaptcha-response');
$url = "https://www.google.com/recaptcha/api/siteverify";
$secretkey = "6LeBGG0UAAAAAEzWMaT0sOjPxcbNwQe7TiWWAknQ";
$response = file_get_contents($url."?secret=".$secretkey."&response=".$form_response."&remoteip=".$_SERVER["REMOTE_ADDR"]);
$data = json_decode($response);
print_r($data);
if (isset($data->success) && $data->success=="true") {
echo "Successfully Passed through captcha";
}
else{
echo "Please Fill captcha";
}
}

You need to provide your private key in here too as the first parameter:
$resp = $this->recaptcha->recaptcha_check_answer ($private_key, $this->input->ip_address(), $this->input->post('recaptcha_challenge_field',true), $this->input->post('recaptcha_response_field',true));
echo "<pre>";print_r($resp);die; #check the response array.

I am working in codeigniter 3.1.5. I have to use this code but not work for me but this code work for me in google recaptcha in google recaptcha in codeigniter 3.1.5.
this is my code for google recaptcha in codeigniter
<script src='https://www.google.com/recaptcha/api.js'></script>
<div class="g-recaptcha" data-sitekey="ADD_YOUR_GOOGLE_SITE_KEY_HERE"></div>
function of google validate captcha
function google_validate_captcha() {
$google_captcha = $this->input->post('g-recaptcha-response');
$google_response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=your secret key here &response=" . $google_captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']);
if ($google_response . 'success' == false) {
return FALSE;
} else {
return TRUE;
}
}
Reference :: http://www.onlinecode.org/integrate-google-recaptcha-codeigniter-validation/

Related

How to compare dynamic url?

I have stored a url in session in laravel. Now i want to compare link between session url which was stored and the url()->previous(). But the problem is url is dynamic.
THe problem i am facing
$url = url('/').'/complete-profile/*';
if(session()->get('url.intended') == $url)
{
return redirect('/home');
}
This doesn't work. how to compare /complete-profile/* with other url.. (*) this can be anything
Try something like this. Builds your URL and the rest check if it contains the word complete-profile :
$url = 'complete-profile';
if (strpos(session()->get('url.intended'), $url) !== false) {
return redirect('/home');
} else {
//
}

Is it wrong to parse the verification from Google?

I used the script from here to do the verification.
The $result === FALSE condition was being bypassed regardless of me clicking on the re-captcha validation on my form.
So I decided to manually parse it like so:
The return looks like this if a failure:
{
"success":false,
"error-codes":[
"missing-input-response"
]
}
And if it's success it looks similar but some additional things are attached, but the main thing I targeted was the string "success":true,
With this part of the script directly below the $result variable:
$result_copy = $result;
// remove white spaces everywhere
$mod_res_copy = preg_replace('/\s+/', '', $result_copy);
$success_string = '"success":true';
if(strpos($mod_res_copy, $success_string) !== false) {
$status = "ok";
}else {
$status = "not-ok";
}
if ($status == "not-ok") {
echo "Please complete the captcha to prevent spam.";
exit;
}else {
// trigger database insert of comment or whatever
}
What I want to know is, is this wrong? Can this be spoofed? I'm using PHP as my server-side scripting language.
You are doing way more work than you need, to parse $result.
It is in JSON format, so this is all you need:
$status = json_decode($result)->success ? 'ok' : 'not-ok';

How to create a slug from title and subtitle in Laravel 5

I want to create a slug. it should be a concatenation of title and subtitle.The following is my code and it's not working, i don't know where i went wrong?
public function setTitleAttribute($value)
{
$this->attributes['main_title'] = ucfirst($value);
$this->attributes['sub_title'] = $value;
if (! $this->exists) {
$this->attributes['slug'] = str_slug($this->attributes['main_title'].$this->attributes['sub_title']);
}
}
I need slug as a combination of main_title+sub_title
public function to_slug ($string) {
$table = array(
'Š'=>'S', 'ı'=>'i', 'ğ'=>'g', 'ü'=>'u', 'ş'=>'s', 'ö'=>'o', 'ç'=>'c', 'Ğ'=>'G', 'Ü'=>'U', 'Ş'=>'S',
'İ'=>'I', 'Ö'=>'O', 'Ç'=>'C',
'š'=>'s', 'Đ'=>'Dj', 'đ'=>'dj', 'Ž'=>'Z', 'ž'=>'z', 'Č'=>'C', 'č'=>'c', 'Ć'=>'C', 'ć'=>'c',
'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss',
'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e',
'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o',
'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
'ÿ'=>'y', 'Ŕ'=>'R', 'ŕ'=>'r',
);
return preg_replace('/[^A-Za-z0-9-]+/', '-', strtr($string, $table) );
}
I'm using this code and its working for me.
It is also good for utf-8.
You can use a laravel package:
https://github.com/cviebrock/eloquent-sluggable
Or I use JavaScript when I sent the form:
https://github.com/madflow/jquery-slugify
I have replicated the exact condition like yours passing static data and its working perfectly in my machine.. try below solution.. do some dd and see whats the combination of the main_title and sub_title is resulting. Also check by removing that if condition once.
$this->attributes['main_title'] = ucfirst($value) . " ";
$this->attributes['sub_title'] = $value;
$slugToUse = $this->attributes['main_title'] . $this->attributes['sub_title'];
if (! $this->exists) {
$this->attributes['slug'] = str_slug($slugToUse);
}
}

Kohana validation client-side ajax

i've been working on a validation script for client-side, that uses built-in Kohana validation, trying to do it in a way that works both client and server sides. So far i made the server side work, but i need some help improving my javascript (My javascript knowlodgement ain't that good) and finish implementing it. (Currently it works for inputs and textareas).
A random controller:
// ...
$errors = array();
if ($this->request->method() == 'POST')
{
// Post to validate/look and get the decoded array
$validate = Request::factory('validate/look')->post($this->request->post())->execute()->body();
$errors = json_decode($validate, TRUE);
// Empty array, Validation OK
if ($errors === array())
{
// anything u want here
}
}
Now, the Validation controller (which will be called from any controller, or via ajax):
class Controller_Validate extends Controller {
public function action_look()
{
//$user = $this->user->loader() ? $this->user : NULL;
//Validation
$valid = Validation::factory($this->request->post())
->rules('name', array(
array('not_empty'),
array('min_length', array(':value', 10)),
array('max_length', array(':value', 80)),
array('regex', array(':value', '/^[\pL\pN ]++$/uD')),
array(array($this, 'check_name')),
))
->rules('description', array(
array('not_empty'),
))
->rule('look_tags', array($this, 'check_tags'))
;
$valid->check();
// Only get messages for the posted fields
$resp = array_intersect_key($valid->errors('uploadlook'), $this->request->post());
$this->response->body(json_encode($resp));
}
}
And this is the javascript:
$(function(){
$('.validate').find('input,textarea').blur(function(){
var element = $(this);
var name = $(this).attr('name');
var value = $(this).val();
$.ajax({
type: 'POST',
url: '/comunidad/validate/look',
data: name + '=' + value,
success: function(e){
e = JSON.parse(e);
if(e.length !== 0) {
var msg = e[name];
var error = '<p>' + msg + '</p>';
if (element.next().length === 0) element.after(error);
else element.next().replaceWith(error);
} else {
if (element.next().length) element.next().remove();
}
}
});
});
});
I need some feedback and little help completing the javascript :)
Some feedback on the code:
The validation code shoud be put in a helper and should just return an array. Then you should have an AJAX-controller that uses the helper and outputs JSON. The serverside check should only use the helper.
That would be much cleaner and the json encode/decode on the server side is pretty ugly when you can just return an array.
What is wrong with the javascript?

cakephp lost session variable when redirect

I have problems with a session variable, users log into the app and then it sets a session variable but when it redirects to the next controller it isn't there.
At the moment I am not using the auth component, I think it is not correct, but I don't know how to apply it to my logic. This is because I dont log in users with username and password, they come authenticated from other website that gives me a ticket and a key to know who they are.
Here is my code of the UsersController where the app starts:
class UsuariosController extends AppController {
public $components = array('Session');
function beforeFilter() {
}
function login() {
$isLogged = false;
if(!empty($_POST['Ffirma']) ) {
$this->loginByTicket();
}
else if(!empty($this->data)) { //When users log by email it works perfectly
$this->loginByEmail();
}
}
private function loginByEmail() {
//Se busca el usuario en la base de datos
$u = new Usuario();
$dbuser = $u->findByEmail($this->data['Usuario']['email']);
//if doesn't exist user in db
if(empty($dbuser) ) {
$this->Session->setFlash('El usuario no existe en el sistema, consulte con el administrador.');
$this->redirect(array('controller' => 'usuarios', 'action' => 'login'));
exit();
}
$this->userIsCorrectlyLogged($dbuser);
}
function loginByTicket() {
$Fip = $_POST['Fip'];
$Frol = $_POST['Frol'];
$FidPersona = $_POST['Fidpersona'];
$Fticket = $_POST['Fticket'];
$Ffirma = $_POST['Ffirma'];
//Check sing
$f = $this->gen_firma($Frol, $FidPersona, $Fticket);
if( strcmp($f, $Ffirma) != 0 ) {
$this->Session->setFlash('Firma no válida.');
return;
}
//Check if ticket is valid
//1º Check if it exists on the db
$t = split('-',$Fticket);
$ticket = new Ticket();
$dbticket = $ticket->findById($t[0]);
if( strcmp($dbticket['Ticket']['valor'], $t[1]) != 0) {
$this->Session->setFlash('Ticket no válido.');
return;
}
//2º if Ip ok
if($Fip != $dbticket['Ticket']['ip']) {
$this->Session->setFlash('IP no válida.'.' '.$dbticket['Ticket']['ip'].' '.$Fip);
return;
}
$u = new Usuario();
$dbuser = $u->findById($dbticket['Ticket']['idPersona']);
$this->userIsCorrectlyLogged($dbuser);
}
private function userIsCorrectlyLogged($dbuser) {
$user = array('Usuario' => array(
'last_login' => date("Y-m-d H:i:s"),
'rol_app' => 1,
'nombre' => $dbuser['Usuario']['nombre'],
'email' => $dbuser['Usuario']['email'],
'apellidos' => $dbuser['Usuario']['apellidos'],
'id' => $dbuser['Usuario']['id']
) );
//Some stuff to determine rol privileges
$this->Session->destroy();
$this->Session->write('Usuario', $user);
$this->redirect(array('controller' => 'mains', 'action' => 'index'),null, true);
exit();
}
As you can see I make some controls before know that the user is correctly logged, and in user correctly logged I just save the session.
In my AppController I check if the user has logged in, but the session variable has already gone:
class AppController extends Controller {
public $components = array('Session');
function beforeFilter() {
//Configure::write('Security.level', 'medium'); //I've tried this that i saw somewhere
pr($this->Session->read()) // Session is empty
if($this->checkAdminSession()) {
$user = $this->Session->read('Usuario');
$email = $user['Usuario']['email'];
$usuario = new Usuario();
$dbuser = $usuario->findByEmail($email);
$respons = $usuario->getAccionesResponsable($dbuser['Usuario']['id']);
$this->set("hayacciones", true);
if( empty($respons) ) $this->set("hayacciones", false);
}
else {
$this->Session->setFlash('Necesitas identificarte para acceder al sistema.');
$this->redirect('/usuarios/login/');
exit();
}
}
function checkAdminSession() {
return $this->Session->check('Usuario');
}
}
I'm desperate, I've read a lot of documentation but I don't know how to solve this problem, could you give me any clue?
Thanks you very much, and sorry for my English!.
Note: I have discovered that if the security level is low it works:
Configure::write('Security.level', 'low');
But I dont like this solution...
You are overriding the beforeFilter() method. So, instead of using this:
<?php
class UsuariosController extends AppController {
function beforeFilter() {
}
you should do this:
<?php
class UsuariosController extends AppController {
function beforeFilter() {
parent::beforeFilter();
}
I was losing session information after a login call too and after searching for a while I found many different ways to fix my issue. I only regret that I don't fully understand what is causing the issue, but I imagine it has to do with php's session configuration.
As you mentioned, changing Security.level to low fixed the issue for me
Configure::write('Security.level', 'low');
Changing the session save configuration to php fixed the issue for me too:
Configure::write('Session', array(
'defaults'=>'cake',
));
And finally adding a timeout worked too (which I ended up using):
Configure::write('Session', array(
'defaults'=>'php',
'cookieTimeout'=> 10000
));
All these found in /app/Config/core.php
I post this hoping someone is able to make sense of what is going on underneath. I feel understanding the root of the issue would make a better job of answering your question.
I have the same problem. I tried all the suggestion. My Cache engine is Apc.
$this->__saveData($t);
debug($this->Session->read());// >>>>>> GOOD
$this->redirect(array('controller'=>'users','action'=>'main'));
}
}
}
function logout() {
$this->Session->destroy();
$this->Session->delete('User');
$this->redirect(array('controller'=>'logins','action'=>'login'));
}
function forgot() {
$this->layout = 'login';
}
private function __saveData($t)
{
$this->Session->write('User',$t['User']['name']);
$this->Session->write('User_name',$t['User']['firstname']);
$this->Session->write('User_id',$t['User']['id']);
$this->Session->write("User_Group",$t['Group']['name']);
$g = $this->Myauth->getPerm('User_Group'); // This is the array of permission w.r.t to the menu (key)
$this->Session->write("Permissions",$g);
debug($this->Session->read());
}
function main()
{
// Check permissions
$this->Myauth->check('users','login');
$username = $this->Session->read('User');
debug($this->Session->read( ));die(); <<<<< NOTHING
}
The funny thing is that yesterday it worked.
My php.ini has a simple extension=apc.so.
My core.php
Configure::write('Session.defaults', 'php');
Nothing change if I change the Security level. I will appreciate any direction.
EDIT
First solution: in my php.ini I had a bad value for session.referer_check (It was = 0 while it should be '').
But now, on the same server, one site is ok. Another one fires the error
Error: Call to undefined function apc_cache_info()
The two sites are separated and do not share any cakelib.
[SOLUTION FOUND]
For Cake > 2.2 and Chrome 24 I found this solution (I tried all the others found on the web). In your core.php:
Configure::write('Security.cookie', 'cakephpfdebackend');
Configure::write('Session.cookieTimeout', 0);
Configure::write('Session.checkAgent', false);
Configure::write('Session.cookie_secure',false);
Configure::write('Session.referer_check' ,false);
Configure::write('Session.defaults', 'php');
Actually, only the Session.cookieTimeout is required. The other settings are optional to solve the problem.
I had some issue with session on some pages . Can you check whether any space comes at the bottom of page after the php ending tag. When i faced this problem, i found session is missing due to a white space character in controller after the php ending tag . Please check this and let me know .
A possible reason for this problem is that the server clock is not synced with the client's clock and thus the cookie timeouts.

Resources