How to send post values in RESTful API using CodeIgniter? - php

I don't have any idea how to get values please help me to sort this problem. Tell me with a reference if someone already has the code then please share. I'm also curious as how to load spark with cURL with a RESTful API with full procedure
<?php class LoginController extends CI_Controller {
public function index()
{
$this->load->view('admin/header');
$this->load->view('admin/index');
$this->load->view('admin/footer');
}
public function loginCon(){
$this->load->Library('rest');
$this->form_validation->set_rules('email', 'E-mail', 'required|trim');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_error_delimiters("<p class='text-danger'>", "</p>");
if ($this->form_validation->run()==false)
{
$email = $this->input->post('email');
$password = $this->input->post('password');
$this->session->set_flashdata('login_failed', 'Invalid User Name Password');
}else{
$config = array('server' => "http://api.amid.tech/hsApiV2/api/demo.php/",
'http_user' => 'admin',
'http_pass' => 'xxxxx',
'http_auth' => 'basic',
);
$this->rest->initialize($config);
$method = 'post';
$param = array(
'UserEmail' => $this->input->post('email'), // works fine here
'UserPass' => $this->input->post('password'),
'UserRoleId'=>1
);
$uri = 'adminlogin';
$this->rest->format('application/json');
$result = $this->rest->{$method}($uri, $param);
echo $result;
$this->load->view('admin/admin_header');
$this->load->view('admin/sidebar');
$this->load->view("admin/dashboard");
$this->load->view('admin/dashboard.php');
}
}
public function registerd()
{
$this->load->view('admin/header');
$this->load->view('admin/registration');
$this->load->view('admin/footer');
}
} ?>

To get raw inputs try
// get the raw POST data
$rawData = file_get_contents("php://input");
For validation try
$this->form_validation->set_rules($rawData['email'], 'E-mail', 'required|trim');

Related

Use form_validation correctly in CodeIgniter

I have a registration system with CodeIgniter but currently I have no control on email and password. A user can register without putting email or a password.
I have an index() and a register_user function() in my Signup controller but the redirection is not working on success
At the moment I have the following code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Signup extends CI_Controller {
public function index()
{
if(!isset($this->session->userdata['sessiondata']['user_id']))
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
if ($this->form_validation->run() == FALSE)
{
$this->load->view('signup-view');
}
else
{
$this->load->view('home-view');
}
}else{
if (intval($this->session->userdata['sessiondata']['user_type']) == 1) {
redirect(base_url().'admin');
} else {
redirect(base_url().'home');
}
}
}
function register_user(){
$this->load->library('custom_u_id');
$data = array('user_id' => $this->custom_u_id->construct_id('USR'),
'name' => $_POST['name'],
'email' => $_POST['email'],
'password' => $_POST['password'],
);
$this->load->model('signup_model');
$user_details = $this->signup_model->register_user($data);
if (!empty($user_details)){
$user_data = array
(
'user_id' => $user_details['user_id'],
'email' => $user_details['email'],
'name' => $user_details['name'],
'user_type' => $user_details['user_type'],
);
$this->session->set_userdata('sessiondata',$user_data);
if (intval($user_details['user_type']) == 1) {
redirect(base_url().'admin');
} else {
redirect(base_url().'home');
}
} else{
redirect('login');
}
}// end of function login
}
Do I need to put the form_validation in my register_user function ? I've tried but the check doesn't work anymore...
I also have in my view the <?php validation_errors();?> function and the <?php form_open(base_url().'signup');?>
looking by your code, i think you want to put register_user() inside validation TRUE since the query is in that method.
so try to change your code to this :
public function index()
{
if(!isset($this->session->userdata['sessiondata']['user_id']))
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
if ($this->form_validation->run() == FALSE)
{
$this->load->view('signup-view');
}
else
{
$this->register_user();
}
}else{
if (intval($this->session->userdata['sessiondata']['user_type']) == 1) {
redirect(base_url().'admin');
} else {
redirect(base_url().'home');
}
}
}
and be sure your form action to like this :
<form action="<?=site_url('/signup/index');?>">

Add user on Codeigniter 3

Hi i am new here and i dont know how to use codeigniter and now im confused. So i am currently trying to add user data to the database using codeigniter 3.1.10 . When i click the " save " button there's nothing to display. The page was refresh
Can you help me please?
Models:
function add_user($data) {
$this->db->set("username",$data["username"]);
$this->db->set("password",$data["password"]);
$this->db->set("indirizzo",$data["indirizzo"]);
$this->db->set("citta",$data["citta"]);
$this->db->set("cap",$data["cap"]);
$this->db->insert("user");
$ins_id =$this->db->insert_id();
return $ins_id;
}
Controllers:
function add() {
$this->load->library('form_validation');
$this->form_validation->set_rules('save', '', 'trim|required|number');
if ($this->form_validation->run()) :
$data = array(
"username"=>$this->input->post("username"),
"password"=>$this->input->post("password"),
"indirizzo"=>$this->input->post("indirizzo"),
"citta"=>$this->input->post("citta"),
"cap"=>$this->input->post("cap"),
);
$user_id= $this->user_model->add_user($data);
$this->log_model->scrivi_log($user_id,"user","add");
$this->session->set_flashdata('feedback', 'User added.');
redirect("user/pageuser/".$user_id);
else :
$content = $this->view->load("content");
$content->load("clienti_form","user/add");
$this->view->render();
endif;
}
Your doing a lot wrong, starting from the fact that your doing stuff from the model in your controller, and you should divide it, otherwise your not using the concept of MVC.
Try something like this, being hard to help you, without seeing the whole code:
Model
function add_user()
{
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'indirizzo' => $this->input->post('indirizzo'),
'citta' => $this->input->post('citta'),
'cap' => $this->input->post('cap')
);
return $this->db->insert('user', $data);
}
Controller
function add() {
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('indirizzo', 'Indirizzo', 'required');
$this->form_validation->set_rules('citta', 'Citta', 'required');
$this->form_validation->set_rules('cap', 'Cap', 'required');
$errore = true;
if ($this->form_validation->run() === FALSE){ // if doesnt work load your view
$this->load->view('your view');
}
else {
$this->user_model->add_user();
$this->log_model->scrivi_log($user_id,"user","add");
$this->session->set_flashdata('feedback', 'User added.');
redirect("user/pageuser/".$user_id);
$content = $this->view->load("content");
$content->load("clienti_form","user/add");
$this->view->render();
}
}
You really should try and search more about it, and learn!
I could learn a lot of the basics of CodeIgniter, watching this channel that has great content, and explains every detail: https://www.youtube.com/playlist?list=PLillGF-RfqbaP_71rOyChhjeK1swokUIS
function add_user($data) {
$this->db->insert("user",$data);
$ins_id =$this->db->insert_id();
return $ins_id;
}
use this in model..
and in controller set rules for each like this
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
// for all other

Codeigniter Sessions not showing data

I have the following error in my code:
1) the data i am storing over session is not showing up in view
2) the form validation set rules is not working.. The required is not working. Whenever i press login without entering any field it prints a.
I have auto loaded session and form validation.
Should I use php sessions or ci sessions?
Controller:
public function loginFormValidation()
{
$this->form_validation->set_rules('email','Username','required'); //not working
$this->form_validation->set_rules('pass','Password','required');
$this->form_validation->set_error_delimiters('<div class = "text-danger">', '</div>');
if($this->form_validation->run())
{
$email = $this->input->post('email');
$pass = $this->input->post('pass');
$this->load->model('loginModel');
$result = $this->loginModel->loginValidation($email,$pass);
$user_id = $result->user_id;
$user_name = $result->user_name;
$password = $result->password;
$arrayDb = array(
'user_id' => $user_id,
'user_name' => $user_name,
'password' => $password,
);
$this->session->set_userdata('row', $arrayDb);
header("location:".base_url()."/Users/dashboard");
}
else
{
echo "a";
}
}
Model:
class loginModel extends CI_Model
{
public function loginValidation($email,$pass)
{
$q = $this->db->where(['email' => $email, 'password' => $pass])
->get('users');
if($q->num_rows())
{
return $q->row();
}
else
{
return false;
}
}
}
Controller where i am printing it for testing:
class Users extends CI_Controller
{
public function dashboard()
{
echo $this->session->userdata('user_name'); // Empty no data showing
exit;
}
}
Your code has a few errors and oversights.
You should NEVER store plaintext passwords, let alone add them to a session variable. There is no need for that. Check out: http://php.net/manual/en/function.password-verify.php
You need to check whether or not the login function actually returned data, otherwise just anyone can "login" as long as they pass form validation.
You are setting session data with an array incorrectly according to the way you want to access the variables.
Controller:
public function loginFormValidation() {
$this->form_validation->set_rules('email', 'Username', 'required');
$this->form_validation->set_rules('pass', 'Password', 'required');
$this->form_validation->set_error_delimiters('<div class = "text-danger">', '</div>');
if ($this->form_validation->run()) {
$email = $this->input->post('email');
$pass = $this->input->post('pass'); // do not store plaintext!!!
$this->load->model('loginModel');
$result = $this->loginModel->loginValidation($email, $pass);
if ($result) {
$user_id = $result->user_id;
$user_name = $result->user_name;
$password = $result->password;
//https://www.codeigniter.com/user_guide/libraries/sessions.html#adding-session-data
$arrayDb = array(
'user_id' => $user_id,
'user_name' => $user_name,
'password' => $password, // why are you storing their PLAINTEXT password in a session?!
);
$this->session->set_userdata($arrayDb);
header("location:" . base_url() . "/Users/dashboard");
} else {
echo 'login failed; bad username/password.';
}
} else {
echo validation_errors();
}
}
Model:
public function loginValidation($email, $pass) {
$q = $this->db->where(['email' => $email, 'password' => $pass])
->get('users');
if ($q->num_rows() == 1) {
return $q->row();
}
return false;
}
Rather than reinventing the wheel check out: https://github.com/benedmunds/CodeIgniter-Ion-Auth
I personally use it an recommend it.

Need to update the users table password field on codeigniter

# table name is users#
## model name is user_model##
### controller name is get_password ###
issue - no change on the password , remain as old
> model(user_model)
public function updatePassword($email,$data)
{
$data1=array('password'=>$data);
$this->db->where('email','$email');
$this->db->update('users','password');
$success = $this->db->affected_rows();
if(!$success){
error_log('Unable to updatePassword');
return false;
}
return true;
}
> controller(get_password)
public function index($rs=FALSE)
{
$this->load->database();
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->model('user_model');
$this->load->library('session');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'password', 'required');
$this->form_validation->set_rules('passconf', 'password Confirmation', 'required|matches[password]');
if ($this->form_validation->run() == FALSE)
{
echo form_open();
$this->load->view('users/fpre');
}
else
{
$data = array(
'password' => md5($this->input->post('password')),
);
$email =array(
'email' =>$this->input->post('email')
);
$this->user_model->updatePassword($data,$email);
echo "Congratulations!";
}
}
it shows no error but the password is not updated remain same at users table..i can't find the problem is, please help me to find it out ..
Controller (get_password):
public function index() {
$this->load->database();
$this->load->helper(array('form', 'url'));
$this->load->library(array('form_validation', 'session'));
$this->load->model('user_model');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'Current password', 'required');
$this->form_validation->set_rules('newpassword', 'password', 'required');
$this->form_validation->set_rules('newpassconf', 'password Confirmation', 'required|matches[newpassword]');
$email = $this->input->post('email');
$success = false;
$msg = '';
if ($this->form_validation->run() !== FALSE) {
$password = md5($this->input->post('password'));
if ($this->user_model->checkPassword($email, $password)){
$newpassword = md5($this->input->post('newpassword'));
if ($this->user_model->updatePassword($email, $newpassword)){
$success = true;
}else{
$msg = 'Unable to updatePassword';
}
}else{
$msg = 'Incorrect password';
}
}
if ($success){
echo 'Congratulations!';
}else{
$this->load->view('users/fpre', array(
'email'=>$email,
'msg'=>$msg
));
}
}
Model (user_model):
public function checkPassword($email, $password) {
$users = $this->db->get_where('users', array('email'=>$email))->row();
return $users->password === $password;
}
public function updatePassword($email, $newpassword) {
$data = array('password' => $newpassword);
$this->db->where('email', $email)
->update('users', $data);
$success = $this->db->affected_rows();
if (!$success) {
error_log('Unable to updatePassword');
}
return $success;
}
View (users/fpre):
if ($msg){
echo 'Message: '.$msg;
}
echo form_open();
echo form_input('email', $email);
echo form_password('password');
echo form_password('newpassword');
echo form_password('newpassconf');
echo form_submit('', 'Enviar');
echo form_close();
Changes to compare:
Your model function shows the parameters are expected to be email and then password, but your controller is passing them through be other way around.
$this->user_model->updatePassword($data,$email);
Should be:
$this->user_model->updatePassword($email,$data);
I also believe the data needs to be passed differently. The where() function expects either where(field_name, value) or where(array(field_name => value)). Looking at your code, you seem to be mixing both of those.
Using set() should help with this too, so instead of
$data1=array('password'=>$data);
$this->db->where('email','$email');
$this->db->update('users','password');
Use:
$this->db->set($data);
$this->db->where($email);
$this->db->update('users');
Note: code untested.
I believe this line $this->db->update('users','password'); should be $this->db->update('users', $data);.
Right now you are not passing the password to the update function. You are passing the string "password".

Codeigniter Signup Controller code review

I just started using a MVC framework, especially Codeigniter and i am having some trouble maintaining my code and where to place my functions(controller or model).
For now i am building a sign up system and i have a controller with the name signup.php
This is my code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Signup extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required|callback_check_valid_username|min_length[6]|max_length[20]|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]|max_length[32]');
if ($this->form_validation->run() == false){
$this->load->view("register/index");
}else{
$this->submitRegistration();
}
}
public function ajaxup(){
if ($this->input->isAjaxRequest()){
header('Content-type: application/json');
$error = false;
$message = '';
$this->form_validation->set_rules('username', 'Username', 'trim|required|callback_check_valid_username|min_length[6]|max_length[20]|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]|max_length[32]');
if ($this->form_validation->run() == false){
$message = validation_errors();
$error = true;
}else{
$this->_submitRegistration();
$message = 'Successfully registered.';
}
$return = array(
'error' => $error,
'message' => $message
);
$return = json_encode($return);
echo $return;
}
}
public function _submitRegistration(){
$username = $this->input->post('username');
$email = $this->input->post('email');
$password = $this->input->post('password');
$data = array(
'username' => $username,
'email' => $email,
'password' => $password
);
$this->load->model('users_model');
$this->users_model->register_user($data);
}
public function check_valid_username($username){
$this->load->model('users_model');
if (!$this->users_model->is_valid_username($username)){
$this->form_validation->set_message('check_valid_username', 'The %s field should contain only letters, numbers or periods');
return false;
}
return true;
}
}
Is there anything i could write better to maintain my code and be readable?
*NOTE:*the function ajaxup is used when a user clicks the button and does an ajax call.
Thanks
Looks pretty good to me. Here are few ideas/suggestions for future improvements:
In index() you are calling $this->submitRegistration() but I think you want to be calling $this->_submitRegistration().
Since you are using the same validation rules in both the index() and ajaxup() methods you could pull pull them out into an array and either make them a property of your controller or put them into a config file.
For documentation see here and here.
$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' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required|min_length[6]|max_length[32]'
),
);
Then in your methods you would do something similar to $this->form_validation->set_rules($validation_rules).
Think about reordering your validation rules. For example, let's take a look at the rules for the username field. If check_valid_username() is making a call to the database (through the user model) then it would probably be better to validate the length requirements before. There's no use making an expensive call to the database if we can determine if the username is invalid.
Make your callback methods private. Right now check_valid_username() is a public method and could potentially be accessed through the URL. Prefix it with an underscore (_check_valid_username()) and then in your validation rules use callback__check_valid_username. Note the two underscores.
If you find yourself needing to use check_valid_username() in multiple controllers you could extend the native form validation library and put it there.
This looks fine to me. You seem to have all the relevant functions located in the user model and you are using the controller to access them. All I can suggest is read up on MVC theory if you feel unsure.
This is a good article:
http://www.codinghorror.com/blog/2008/05/understanding-model-view-controller.html

Categories