I've asked this subject in another topic but that topic has gone cold and I've directed this topic to the core of the problem.
I've loaded the session library in the previous page and have no issue with the function working in that page.
But it is the next page where I'm having problems. I get the error "Unexpected T_VARIABLE".
I've read the topic on How to solve syntax errors. That topic suggests the line before is usually the problem line, usually by a missing semicolon or bracket.
This is the coding;
public function index()
{
$this->load->model('Code_model', 'code_model');
$this->session->email //This is the problem line
$email = $this->session->email
$code = $this->input->post('code');
if ($this->code_model->find_code($email, $code))
{
$this->load->view('username');
}
else
{
$this->load->view('codeincorrect');
}
}
I've tried putting a semicolon at the end. And tried adding - userdata('email');
And tried having a separate function containing the problem line with its own brackets. And tried deleting the problem line & the line below. When deleted $email cannot be found.
But nothing works.
Is there somebody who understands how sessions work and how they can be integrated into a function?
Update
This is the Controller coding of the previous page, which works good.
function __construct()
{
parent::__construct();
$this->load->library('session');
}
public function index()
{
$this->load->model('Email_model', 'email_model');
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'email', 'required|min_length[10]|max_length[40]|valid_email|is_unique[tbl_members.email_address]', array(
'required' => 'You have not entered an %s address.', 'min_length' => 'Your %s address must be a minimum of 10 characters.',
'max_length' => 'Your %s address must be a maximum of 40 characters.', 'valid_email' => 'You must enter a valid %s address.',
'is_unique' => 'That %s address already exists in our Database.'));
if ($this->form_validation->run() == FALSE) // The email address does not exist.
{
$this->load->view('email');
}
else
{
$email = $this->input->post('email');
$random_string = chr(rand(65,90)) . rand(1,9) . chr(rand(65,90)) . rand(1,9) . chr(rand(65,90)) . chr(rand(65,90));
$code = $random_string;
$this->email_model->insert_email($email, $code);
}
}
2nd Update - This is the coding for the 2 Controllers and 2 Models
Email Controller
class Email extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->library('session');
}
public function index()
{
$this->load->model('Email_model', 'email_model');
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'email', 'required|min_length[10]|max_length[40]|valid_email|is_unique[tbl_members.email_address]', array(
'required' => 'You have not entered an %s address.', 'min_length' => 'Your %s address must be a minimum of 10 characters.',
'max_length' => 'Your %s address must be a maximum of 40 characters.', 'valid_email' => 'You must enter a valid %s address.',
'is_unique' => 'That %s address already exists in our Database.'));
if ($this->form_validation->run() == FALSE) // The email address does not exist.
{
$this->load->view('email');
}
else
{
$email = $this->input->post('email');
$random_string = chr(rand(65,90)) . rand(1,9) . chr(rand(65,90)) . rand(1,9) . chr(rand(65,90)) . chr(rand(65,90));
$code = $random_string;
$this->email_model->insert_email($email, $code);
$this->load->library('email'); // Not sure if this works - testing from localhost
$this->email->from('<?php echo WEBSITE_NAME; ?>', '<?php echo WEBSITE_NAME; ?>'); // Not sure if this works - testing from localhost
$this->email->to('$email'); // Not sure if this works - testing from localhost
$this->email->subject('Code.'); // Not sure if this works - testing from localhost
$this->email->message('Select & Copy this code, then return to the website. - ','$code'); // Not sure if this works - testing from localhost
$this->email->send(); // Not sure if this works - testing from localhost
$this->load->view('code');
}
}
}
Email Model
class Email_model extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
}
public function insert_email($email, $code)
{
$data = array(
'email_address' => $email,
'pass_word' => $code
);
$this->db->insert('tbl_members', $data);
return $this->db->insert_id();
}
}
Code Controller
class Code extends CI_Controller
{
public function index()
{
$this->load->model('Code_model', 'code_model');
$this->session->email // Problem line - syntax error, unexpected '$email' (T_VARIABLE)
$email = $this->session->email
$code = $this->input->post('code');
if ($this->code_model->find_code($email, $code))
{
$this->load->view('username');
}
else
{
$this->load->view('codeincorrect');
}
}
}
Code Model
class Code_model extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
}
public function find_code($code,$email)
{
$this->db->select('user_id');
$this->db->where('email_address', $email);
$this->db->where('pass_word', $code);
$code = $this->db->get('tbl_members');
if ($code->result())
{
return $this->db->delete('pass_word', $code);
}
}
}
Make sure the sessions library is loaded. You can do this manually by saying:
$this->load->library('session');
But if you want it loaded at all times, go to your autoload.php file and make sure sessions is added in the autoload['libraries'] area.
Your code looks like the buggy. Please check followings.
In PHP statements are ended by semi-colon (;)
$this->session->email : returns the value of email element from session array and it should be assigned, like the next line as in your code $email = $this->session->email.
Check whether the email is set in the session or not print_r($this->session->all_userdata());
Best of luck!
Related
I am getting Undefined Variable email under Controllers.
Controller : login.php
public function index() {
$this->load->view('bootstrap/header');
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->load->model('Login_db');
$is_exist = $this->Login_db->isEmailExist($email);
if ($is_exist) {
$this->form_validation->set_message('isEmailExist', 'Email Address Already Exists!');
return FALSE;
} else {
return TRUE;
}
$this->load->view('bootstrap/footer');
}
Model : login_db.php
public function isEmailExist($email) {
$this->db->select('user_id');
$this->db->where('email', $email);
$query = $this->db->get('login');
if ($query->num_rows() > 0) {
return TRUE;
} else {
return FALSE;
}
}
I have to check whether email exists are not.
before
$is_exist = $this->Login_db->isEmailExist($email);
add this (in case of a POST request)
$email = $this->input->post('email');
or this ((in case of a GET request)
$email = $this->input->get('email');
by checking your code i came to assume that you want to allow only the emails which is already not in table ? why have not you validated with is_unique like
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[login.email]');
or you can change the line as
$this->Login_db->isEmailExist($this->input->post('email'));
or you should define $email before passing it / calling the function
$email=$this->input->post('email');
for custom massaging :
$this->form_validation->set_rules( 'email', 'Email', 'required|valid_email|is_unique[login.email]', array( 'is_unique' => 'Email already exists' ) );
better you go through the manual
https://www.codeigniter.com/user_guide/libraries/form_validation.html
the var $email used here
$is_exist = $this->Login_db->isEmailExist($email); line 5 of index
is never isntanciate. You should instantiate it to avoir error.
Codeigniter throw the next error when trying to render the register page. It looks like the method Register::render() is not defined on line 21 but i don't understand the problem at all
The Register.php file
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Register extends MY_Controller
{
public function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('first_name', 'First name','trim|required');
$this->form_validation->set_rules('last_name', 'Last name','trim|required');
$this->form_validation->set_rules('username','Username','trim|required|is_unique[users.username]');
$this->form_validation->set_rules('email','Email','trim|valid_email|required');
$this->form_validation->set_rules('password','Password','trim|min_length[8]|max_length[20]|required');
$this->form_validation->set_rules('confirm_password','Confirm password','trim|matches[password]|required');
if($this->form_validation->run()===FALSE)
{
$this->load->helper('form');
$this->render('register/index_view');
}
else
{
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$username = $this->input->post('username');
$email = $this->input->post('email');
$password = $this->input->post('password');
$additional_data = array(
'first_name' => $first_name,
'last_name' => $last_name
);
$this->load->library('ion_auth');
if($this->ion_auth->register($username,$password,$email,$additional_data))
{
$_SESSION['auth_message'] = 'The account has been created. You may now login.';
$this->session->mark_as_flash('auth_message');
redirect('user/login');
}
else
{
$_SESSION['auth_message'] = $this->ion_auth->errors();
$this->session->mark_as_flash('auth_message');
redirect('register');
}
}
}
}
You should use:
$this->load->view('register/index_view');
When I started with codeigniter I had a similar issue. Render() is used by some libraries and, like you, I followed a tutorial, but there was nothing about that library. After a while I saw some comments in that article and I found out about render(). If you want to use this, try to find some library that has it implemented.
I'm trying to create a form validation callback function but I'm having a little trouble getting my head around it.
What I am trying to do is create a contact form where with a join the mailing list option. If the option to join the mailing list is checked I want the name and email of the person to be added to the mailing list database. This part works perfectly however I also want the function to check the database to ensure that the email address being added is unique and this is the bit that I just can't get my head around.
Controller:
public function contact()
{
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'your name', 'required', array('required'=>"<p class='required'>Please provide %s</p><br>"));
$this->form_validation->set_rules('email', 'your email address', 'required', array('required'=>"<p class='required'>Please provide %s</p><br>"));
if($this->form_validation->run() == FALSE)
{
$this->load->view('templates/headder');
$this->load->view('contact');
$this->load->view('templates/footer');
}
else
{
$this->load->library('email');
$name = $this->input->post('name');
$email = $this->input->post('email');
$phone = $this->input->post('phone');
$message = $this->input->post('message');
$list = $this->input->post('mailing_list');
$email_message = "Name: $name<br>Email: $email<br>Phone: $phone<br>Message:<br>$message";
$this->email->initialize();
$this->email->from($email, $name);
$this->email->to('myaddress#mydomain.co.uk');
$this->email->subject('New Query');
$this->email->message($email_message);
$this->email->send();
if($this->email->send()){
$this->load->view('send_error');
}
else
{
if($list == 'no')
{
$this->load->view('sent');
}
else
{
$this->form_validation->set_rules('email', 'Email', 'is_unique[mail_list, email]');
if($this->form_validation->run() == FALSE)
{
$this->load->model('mailing_listm');
$this->mailing_listm->add_name();
$this->load->view('sent');
}
else
{
$this->load->view('contact');
}
}
}
}
}
Error Message:
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' email 'myaddress#mydomain.co.uk' LIMIT 1' at line 3
SELECT * FROM `mail_list`, `email` WHERE mail_list, email 'myaddress#mydomain.co.uk' LIMIT 1
Filename: libraries/Form_validation.php
Line Number: 1134
Hopefully someone will be able to let me know what daft thing I've done this time.
Also, This function is turning into a bit of a monster, it's the most complicated thing I've every tried to write. Is there any way that I can split it out so that it is made up of several smaller functions instead of one gargantuan one?
Thanks,
EDIT
I have updated my code in line with the comment below about using is_unique however now I am receiving an error message.
EDIT
Model:
Public function add_name()
{
$this->name = $this->input->post('name');
$this->email = $this->input->post('email');
$this->db->insert('mail_list', $this);
}
for checking unique field there is a validation rule in codeigniter.
is_unique[table.field]
I want to limit my registration to emails with #mywork.com I made the following in My_Form_validation.
public function email_check($email)
{
$findme='mywork.com';
$pos = strpos($email,$findme);
if ($pos===FALSE)
{
$this->CI->form_validation->set_message('email_check', "The %s field does not have our email.");
return FALSE;
}
else
{
return TRUE;
}
}
I use it as follows. I use CI rules for username and password and it works, for email it accepts any email address. Any I appreciate any help.
function register_form($container)
{
....
....
/ Set Rules
$config = array(
...//for username
// for email
array(
'field'=>'email',
'label'=>$this->CI->lang->line('userlib_email'),
'rules'=>"trim|required|max_length[254]|valid_email|callback_email_check|callback_spare_email"
),
...// for password
);
$this->CI->form_validation->set_rules($config);
The problem with creating a callback directly in the controller is that it is now accessible in the url by calling http://localhost/yourapp/yourcontroller/yourcallback which isn't desirable. There is a more modular approach that tucks your validation rules away into configuration files. I recommend:
Your controller:
<?php
class Your_Controller extends CI_Controller{
function submit_signup(){
$this->load->library('form_validation');
if(!$this->form_validation->run('submit_signup')){
//error
}
else{
$p = $this->input->post();
//insert $p into database....
}
}
}
application/config/form_validation.php:
<?php
$config = array
(
//this array key matches what you passed into run()
'submit_signup' => array
(
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required|max_length[255]|valid_email|belongstowork'
)
/*
,
array(
...
)
*/
)
//you would add more run() routines here, for separate form submissions.
);
application/libraries/MY_Form_validation.php:
<?php
class MY_Form_validation extends CI_Form_validation{
function __construct($config = array()){
parent::__construct($config);
}
function belongstowork($email){
$endsWith = "#mywork.com";
//see: http://stackoverflow.com/a/619725/568884
return substr_compare($endsWith, $email, -strlen($email), strlen($email)) === 0;
}
}
application/language/english/form_validation_lang.php:
Add: $lang['belongstowork'] = "Sorry, the email must belong to work.";
Are you need validation something like this in a Codeigniter callback function?
$this->form_validation->set_rules('email', 'email', 'trim|required|max_length[254]|valid_email|xss_clean|callback_spare_email[' . $this->input->post('email') . ']');
if ($this->form_validation->run() == FALSE)
{
// failed
echo 'FAIL';
}
else
{
// success
echo 'GOOD';
}
function spare_email($str)
{
// if first_item and second_item are equal
if(stristr($str, '#mywork.com') !== FALSE)
{
// success
return $str;
}
else
{
// set error message
$this->form_validation->set_message('spare_email', 'No match');
// return fail
return FALSE;
}
}
A correction to Jordan's answer, the language file that you need to edit should be located in
system/language/english/form_validation_lang.php
not application/.../form_validation_lang.php. If you create the new file under the application path with the same name, it will overwrite the original in the system path. Thus you will lose all the usage of the original filters.
I have a form on my website header where i allow the user to log in with his username/password... then i POST to /signin page and check if the username exists to allow the user to log in.. if there is a problem upon login i output these errors...
i tried using the following code to show a custom error but with no luck
if ($this->form_validation->run() == false){
$this->load->view("login/index", $data);
}else{
$return = $this->_submitLogin();
if ($return == true){
//success
}else{
$this->form_validation->set_message('new_error', 'error goes here');
//error
}
$this->load->view("login/index", $data);
}
how does set_message work and if this is the wrong method, which one allow me to show a custom error in this case?
EDIT :
validation rules:
private $validation_rules = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'trim|required|callback__check_valid_username|min_length[6]|max_length[20]|xss_clean'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required|min_length[6]|max_length[32]'
),
);
The set_message method allows you to set your own error messages on the fly. But one thing you should notice is that the key name has to match the function name that it corresponds to.
If you need to modify your custom rule, which is _check_valid_username, you can do so by perform set_message within this function:
function _check_valid_username($str)
{
// Your validation code
// ...
// Put this in condition where you want to return FALSE
$this->form_validation->set_message('_check_valid_username', 'Error Message');
//
}
If you want to change the default error message for a specific rule, you can do so by invoking set_message with the first parameter as the rule name and the second parameter as your custom error. E.g., if you want to change the required error :
$this->form_validation->set_message('required', 'Oops this %s is required');
If by any chance you need to change the language instead of the error statement itself, create your own form_validation_lang.php and put it into the proper language folder inside your system language directory.
As you can see here, you can display the custom error in your view in the following way:
<?php echo form_error('new_error'); ?>
PS: If this isn't your problem, post your corresponding view code and any other error message that you're getting.
The problem is that your form is already validated in your IF part! You can fix the problem by this way:
if ($this->form_validation->run() == false){
$this->load->view("login/index", $data);
}else{
$return = $this->_submitLogin();
if ($return == true){
//success
}else{
$data['error'] = 'Your error message here';
//error
}
$this->load->view("login/index", $data);
}
In the view:
echo $error;
The CI way to check user credentials is to use callbacks:
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
...
public function username_check($str) {
// your code here
}
I recommend you to read CI documentation: http://codeigniter.com/user_guide/libraries/form_validation.html
The way I did this was to add another validation rule and run the validation again. That way, I could keep the validation error display in the view consistent.
The following code is an edited excerpt from my working code.
public function login() {
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$data['content'] = 'login';
if($this->form_validation->run()) {
$sql = "select * from users where email = ? and password = ?";
$query = $this->db->query($sql, array($this->input->post('email'), $this->input->post('password')));
if($query->num_rows()==0) {
// user not found
$this->form_validation->set_rules('account', 'Account', 'callback__noaccount');
$this->form_validation->run();
$this->load->view('template', $data);
} else {
$this->session->set_userdata('userid', $query->id);
redirect('/home');
}
} else {
$this->load->view('template', $data);
}
}
public function _noaccount() {
$this->form_validation->set_message('_noaccount', 'Account must exist');
return FALSE;
}
Require Codeigniter 3.0
Using callback_ method;
class My_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->form_validation->set_message('date_control', '%s Date Special Error');
}
public function date_control($val, $field) { // for special validate
if (preg_match("/^[0-9]{2}.[0-9]{2}.[0-9]{4}$/", $val)) {
return true;
} else {
return false;
}
}
public function my_controller_test() {
if ($this->input->post()) {
$this->form_validation->set_rules('date_field', 'Date Field', 'trim|callback_date_control[date_field]|xss_clean');
if ($this->form_validation->run() == FALSE) {
$data['errors']=validation_errors();
$this->load->view('my_view',$data);
}
}
}
}
Result:
if date = '14.07.2017' no error
if date = '14-7-2017' Date Field Date Special Error