How to send email in codeigintier? - codeigniter

I have done a code for send email to a emailid in codeigniter as shown below :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Data extends CI_Model
{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function insertStu($newStuData){
$stuData = array(
'stu_fullname' => $newStuData['stuFullname'],
'stu_username' => $newStuData['stuUsername'],
'stu_password' => $newStuData['stuPassword'],
'stu_email' => $newStuData['stuEmail'],
'stu_modified_date' => date('y-m-d')
);
$from_email = "annanitababu.19#gmail.com";
$to_email = $newStuData['stuEmail'];
//Load email library
$this->load->library('email');
$this->email->from($from_email, 'Anu');
$this->email->to($to_email);
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');
$this->email->send();
$this->db->insert('sb_stu', $stuData);
return ($this->db->affected_rows() == 1) ? true : false;
}
}
?>
I wanted to send a link of a page as the contents of the message in the send() as a mail to the email id and upon clicking the link in the mail, it should update a particular field in a table which is initially '0' to '1' in the database. Can anyone suggest a solution for this ?

Add link to in the message body and generate encoded unique identification number . The number in link and stored in your db. The user click on that link , decode the unique and match in the table. if found change status 0 to 1.
Example : https://www.amazonsoldout.com/
which also in codeigniter.

Related

Custom Validation connected to database working on localhost but not on remote sever

I have created MY_Form_validation that extends CI_Form_validation. I have loaded the library in Customer Controller. The validate_email function in customer model checks whether the customer exists while logging in. It is working fine on localhost but the method always returns false on the remote server even when a user actually exists. What could be wrong?
I have loaded the library like this
$this->load->library('form_validation');
Login email validation rules
$validate_data = array(
array(
'field' => 'login_email',
'label' => 'Email',
'rules' => 'trim|required|validate_email|is_active|xss_clean'
)
);
My_Form_validation library
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
public function __construct(){
parent::__construct();
}
public function validate_email($field){
$this->CI->load->model('customer_model');
$email = $this->CI->customer_model->validate_email($field);
if($email === true){
return true;
}else{
$this->set_message('validate_email','The {field} does not exist');
return false;
}
}//end method validate_email
}
?>
Validate email model function
public function validate_email($email){
$sql = "SELECT `customer_id` FROM `customer` WHERE `email` = ? AND `status` != -1";
$query = $this->db->query($sql,array($email));
return ($query->num_rows() == 1) ? true : false;
}//end method validate_email
I like using -1 to represent deleted accounts in my databases
I am also autoloading my database
I had the a similar problem. According to the database configurations in codeigniter database.php, I noticed the following
char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
So i dropped my database and recreated it. Changed my database collation to utf8_general_ci and changed my tables charset from armscii8 to utf8 and everything worked
By trusting your words about the data that is currently on your database your function should work, but I would advise you to change the model validate function to something more similiar to CodeIgniter approach.
public function validate_email($email)
{
$this->db->where('email', $email)
->where('status !=', '-1');
$query = $this->db->get('customer');
if($query->num_rows() > 0)
return TRUE;
}
Secondly, create a function to retrieve all the results according to your where condition.
public function getAllEmailsByEmail($email)
{
$this->db->where('email', $email)
->where('status !=', '-1');
return $this->db->get('customer')->result();
}
And just check out many rows it's returned.
print_r($this->CI->customer_model->getAllEmailsByEmail($field));

how to get a passed data from the url in codeigniter

Hi i have this data passed in the url
http://www.test.com/dashboard/john-doe
i want to get the page when i enter http://www.test.com/dashboard/john-doe
john doe is a name from the database i retrieve when the users can login.
so dashboard is a controller then how will i able to get the page if i passed a data john-doe next to dashboard controller? can someone help me figured this thing out? Any help is muchly appreicated this is my controller below
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Dashboard extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('users_model', 'um');
$sessionData = $this->session->userdata('loggedIn');
$this->data['id'] = $sessionData['userID'];
if(!$this->session->userdata('loggedIn')){
redirect('login');
}
}
public function index($slug){
echo $slug; exit;
$this->data['title'] = 'Dashboard | test';
$this->data['menu'] = 'dashboard';
//get CustomerInfo
$this->data['getCustomerInfo'] = $this->um->getCustomerInfo($this->data['id']);
$this->template_lib->set_view('templateLogIn', 'dashboard', $this->data,'',$this->data);
}
}
The index function is loaded by default if the second segment of the URI is empty. If you have parameters you need to define a route:
$route['dashboard/(:any)'] = "dashboard/index/$1";

sending email with codeigniter

I have this MODEL and I get the email which I want to send
class Cliente_Model extends CI_Model{
public function getInfo($id){
$this->db->select('*');
$this->db->from('pendientes');
$query = $this->db->get();
if($query->num_rows() > 0)
{
foreach ($query->result_array() as $row)
{
return $row['email'];
}
}
else
{
return FALSE;
}
}
}
CONTROLLER
$this->load->model('cliente_model', 'client');
$clientInfo = $this->client->getInfo($id);
$this->email->from('myemail#gmail.com', 'Demo');
$this->email->to($clientInfo);
$this->email->subject('Email Test');
$this->email->message('your user is '.$clientInfo.' and your password is '.$clave);
$this->email->send();
and I need some help here, I can get the email and it can send it perfectly but in the message I need to send the password also and I don't know how I can get it from the model.
thanks in advance!
Instead of returning '$row['email]' from your model, you should return the whole '$row' which will enable you to get other data from the model and not only the email field.
Not sure, but you might need to use it like this in the controller:
$this->email->message('your user is '.$clientInfo->email.' and your password is '.$clientInfo->passwordField);
Good luck.

codeigniter email->send being send twice

i am using codeigniter 2 with the tank_auth library.
in the model named user_model it has an function (_send_email()) to send an email:
function _send_email($type, $email, &$data)
{
$this->load->library('email');
$this->config->set_item('language', 'dutch');
$this->email->set_newline("\r\n");
$this->email->from($this->config->item('webmaster_email', 'tank_auth'), $this->config->item('website_name', 'tank_auth'));
//$this->email->reply_to($this->config->item('webmaster_email', 'tank_auth'), $this->config->item('website_name', 'tank_auth'));
$this->email->to($email);
$this->email->subject(sprintf($this->lang->line('auth_subject_'.$type), $this->config->item('website_name', 'tank_auth')));
$this->email->message($this->load->view('email/'.$type.'-html', $data, TRUE));
$this->email->set_alt_message($this->load->view('email/'.$type.'-txt', $data, TRUE));
if($this->email->send()){
echo "sendit";
}
}
i try to call this function from a controller like this:
public function email($value='')
{
$this->lang->load('tank_auth', 'dutch');
$this->load->model('user_model');
$data = array("site_name" => "site name");
$this->user_model->_send_email('bestelling_geplaatst', "my_email#hotmail.com",$data); // send
}
the problem is that the email is being sent twice to the email adres
anyone who run across this problem an know's where to look for an solution ( or the problem)
More info:
i am trying to make a method in my controller just like the example in the use guide like here: https://www.codeigniter.com/user_guide/libraries/email.html
$this->load->library('email');
$this->email->from('your#example.com', 'Your Name');
$this->email->to('someone#example.com');
$this->email->cc('another#another-example.com');
$this->email->bcc('them#their-example.com');
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');
$this->email->send();
This method also sends the email twice!
The reason is i have the plugin Firebug Lite for Google Chrome. after i deactivated this the page only requested once!
found awnser right here:
https://stackoverflow.com/a/10580841/1108772
Thanks everyone for replying and all you help
First of all, This is wrong approach. Use model function only to interactive with database. The function that sends the mail should be in controller.
Remove this code
if($this->email->send())
{
echo "sendit";
}
from
function _send_email($type, $email, &$data)

codeigniter datamapper relationship validation issues

I need to set up the validation rules to validate the related items on a specific object, ie: A user can have no more than 3 products related to it.
I believe DataMapper can check for this validation using _related_max_size rule, but I can't figure out how to use it on the $validation array in the model.
So far I've tried this in both my user and product models:
var $validation = array(
'product' => array(
'rules' => array('max_size' => 3)
)
);
Can somebody show me an example on how to set up this at the model, controller and finally the view?
Edit: What I mean is, a user has many products, and can create a certain amount of them, let's say 3 products, when that amount is reached, the user can no longer create products, and this validation rule should not permit the user to create more products.
This would be the DB Schema:
Users table
------------------
id | username |
------------------
Products table
------------------------
id | user_id | name |
------------------------
More info here: http://codeigniter.com/forums/viewthread/178045/P500/
Thanks!
EDIT:
Ok, I got it all working now… Except, I need to do the following:
var $validation = array(
'product' => array(
'label' => 'productos',
'rules' => array('required','max_size' => $products_limit)
)
);
The $products_limit comes from the “plan” the user has associated, and it’s stored in the session when the user logs in. When I try to run this I get:
Parse error: syntax error, unexpected T_VARIABLE in /var/www/stocker/application/models/user.php on line 11
Is there any way to make this setting dynamic?
In model
var $validation = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => array('required')
)
);
In controller. $this -> $object = new Your_model();
$object->validate();
if ($object->valid)
{ $object->save();
// Validation Passed
}
else
{ $data['error'] = $object->error;
// Validation Failed
}
In view.
echo $error->field_name
I never use Codeigniter before, but give me a chance to help you. So far I didn't found any built-in validation in Code-igniter (correct me if I'm wrong).
One workaround that I could think of is to Callback:Your own Validation Functions. Below is a snip. Pardon me if it didn't work as you want.
In Model: (create something like)
function product_limit($id)
{
$this->db->where('product_id',$id);
$query = $this->db->get('products');
if ($query->num_rows() > 3){
return true;
}
else{
return false;
}
}
In controller: (create something like)
function productkey_limit($id)
{
$this->product_model->product_exists($id);
}
public function index()
{
$this->form_validation->set_rules('username', 'Username', 'callback_product_limit');
}
For more information Please refer to the manual page which gives more complete. I am also new to CodeIgniter. But I hope this helps you, not complicate you.
First, set up a custom validation rule in libraries/MY_Form_validation.php
If the file doesn't exist, create it.
Contents of MY_Form_validation.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation
{
function __construct($config = array())
{
parent::__construct($config);
}
function valid_num_products()
{
//Perhaps it would be better to store a maxProducts column in your users table. That way, every user can have a different max products? (just a thought). For now, let's be static.
$maxProducts = 3;
//The $this object is not available in libraries, you must request an instance of CI then, $this will be known as $CI...Yes the ampersand is correct, you want it by reference because it's huge.
$CI =& get_instance();
//Assumptions: You have stored logged in user details in the global data array & You have installed DataMapper + Set up your Product and User models.
$p = new Product();
$count = $p->where('user_id', $CI->data['user']['id'])->count();
if($count>=$maxProducts) return false;
else return true;
}
}
Next, set up your rule in config/form_validation.php.
Contents of form_validation.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config = array
(
'addProduct' => array
(
array
(
'field' => 'name',
'label' => 'Product Name',
'rules' => 'required|valid_num_products'
)
)
);
Next, set up your error message in language/english/form_validation_lang.php. Add the following line:
$lang['valid_num_products'] = "Sorry, you have exceeded your maximum number of allowable products.";
Now in the Controller, you'll want something along the lines of:
class Products extends MY_In_Controller
{
function __construct()
{
parent::__construct();
$this->load->library('form_validation');
}
function add()
{
$p = $this->input->post();
//was there even a post to the server?
if($p){
//yes there was a post to the server. run form validation.
if($this->form_validation->run('addProduct')){
//it's safe to add. grab the user, create the product and save the relationship.
$u = new User($this->data['user']['id']);
$x = new Product();
$x->name = $p['name'];
$x->save($u);
}
else{
//there was an error. should print the error message we wrote above.
echo validation_errors();
}
}
}
}
Finally, you might wonder why I've inherited from MY_In_Controller. There is an excellent article written by Phil Sturgeon over on his blog entitled Keeping It Dry. In the post he explains how to write controllers that inherit from access-controlling Controllers. By using this paradigm, controllers that inherit from MY_In_Controller can be assumed to be logged in, and the $this->data['user']['id'] stuff is therefore assumed to be available. In fact, $this->data['user']['id'] is SET in MY_In_Controller. This helps you seperate your logic in such a way that you're not checking for logged in status in the constructors of your controllers, or (even worse) in the functions of them.

Resources