making code igniter registration form [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
So I am making a form for people to register but its not working, and for some reason my debugger in netbeans is not working so I cannot check properly.
This is the html form
<?php
if(validation_errors() != false)
{
echo '<div class="form-group alert alert-danger alert-box has-error">';
echo'<ul>';
echo validation_errors('<li class="control-label">', '</li>');
echo'</ul>';
echo '</div>';
}
/* form-horizontal */
echo form_open('main/insertInformation');
?>
<div class="form-group">
<input type="text" name="name" class="form-control input-lg" placeholder="Name">
</div>
<div class="form-group">
<input type="email" name="email" class="form-control input-lg" placeholder="Email">
</div>
<div class="form-group">
<input type="text" name="phone" class="form-control input-lg" placeholder="Phone">
</div>
<div class="form-group">
<input type="password" name="password" class="form-control input-lg" placeholder="Password">
</div>
<div class="form-group">
<input type="password" name="password_confirm" class="form-control input-lg" placeholder="Confirm Password">
</div>
<div class="form-group">
<button type='submit' class="btn btn-primary btn-lg btn-block">Sign In</button>
</div>
</div>
Then I try to get all this information to my controller like this
public function insertInformation(){
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('phone', 'Phone', 'required');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[4]|max_length[32]');
$this->form_validation->set_rules('password_confirm', 'Password Confirm', 'required|matches[password]');
if ($this->form_validation->run() == FALSE){
$this->load->view('header_view');
$this->load->view('login_view');
$this->load->view('footer_view');
}else{
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'phone' => $this->input->post('phone'),
'password' => $this->input->post('password')
);
$this->db->trans_begin();
$this->load->model('main_page');
$this->main_page->storeRegisterInfo($data);
$message['account_created'] = 'Your account has been created';
$this->load->view('admin_view', $message);
}
}
And here is the model ,
public function storeRegisterInfo($data){
$insert = $this->db->insert('new_users',$data);
return $insert;
}
and my database looks like this
I am pretty new to codeigniter so I am pretty sure there is alot of errors here, so please do help me out and please do explain me in steps for a better understanding. Thanks!
THis is the error

After long discussion for specific for this error only you missed to load the model you need to load your model as:
$this->load->model('main_page');
UPDATE 1:
Removal of $this->db->trans_begin(); solved your problem but i think its not a complete solution.
If you want to use Transactions than make sure you can only apply this for InnoDB or BDB table types not for MyISAM.
If you are using InnoDB and want to use trans_begin() than make sure after execution of all queries you need to use trans_commit() otherwise this will not display anything in your database.
From the User Guide:
$this->db->trans_begin(); // transaction start
$this->db->query('AN SQL QUERY...');
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback(); // rollback if failure
}
else
{
$this->db->trans_commit(); // commit if success
}

Remove this part, all should work then
$this->db->trans_begin();

When we write an model file, we have set of conditions. One of that is model file should contain word of _model. (Ex: user_model, registration_model)
So your model should also be changed. Now your model looks like main_page change it, (ex: main_model, page_model).
File name should be Main_model.php
Inside your model
class Main_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
}
This is how Codeigniter use the Model.

Related

Unable to preserve input values after form validation Codeigniter 4

This is a question I have seen asked before but I have been unable to find an answer for the newer version of Codeigniter.
Controller
<?php
namespace App\Controllers;
class SendEmail extends BaseController
{
public function index($validation = NULL){
// Load form helper
helper('form');
// Instantiate session
$session = \Config\Services::session();
// Set css, javascript, and flashdata
$data = [
'css' => array('contact.css'),
'js' => array('contact.js'),
'validation' => $validation,
'success' => $session->get('success')
];
// Show views
echo view('templates/header', $data);
echo view('contact', $data);
echo view('templates/footer', $data);
}
public function sendEmail(){
// Instantiate request
$request = $this->request;
// Captcha API
$captchaUser = $request->getPost('g-recaptcha-response');
// Captcha Key loaded from a file left out of the repo
$captchaConfig = config('Config\\Credentials');
$captchaKey = $captchaConfig->captchaKey;
$captchaOptions = [
'secret' => $captchaKey,
'response' => $captchaUser
];
$client = \Config\Services::curlrequest();
$captchaResponse = $client->request('POST', 'https://www.google.com/recaptcha/api/siteverify', ['form_params' => $captchaOptions]);
$captchaObj = json_decode($captchaResponse->getBody());
// Load validation library
$validation = \Config\Services::validation();
// Set validation rules
$validation->setRules([
'name' => 'required|alpha_dash|alpha_space',
'email' => 'required|valid_email',
'subject' => 'required|alpha_numeric_punct',
'message' => 'required|alpha_numeric_punct'
]);
// Validate inputs
if (!$this->validate($validation->getRules())){
// Run index function to show the contact page again
$this->index($this->validator);
}
// Validate captcha
elseif(!$validation->check($captchaObj->success, 'required')){
$validation->setError('captcha','Did not pass captcha. Please try again.');
$this->index($validation->getErrors());
}
else{
// Set variables to input
$name = $request->getPost('name');
$email = $request->getPost('email');
$subject = $request->getPost('subject');
$message = $request->getPost('message');
// Load email class
$emailC = \Config\Services::email();
// Set email settings
$emailC->setFrom('bensirpent07#benkuhman.com', $name);
$emailC->setReplyTo($email);
$emailC->setTo('benkuhman#gmail.com');
$emailC->setSubject($subject);
$emailC->setMessage($message);
// Testing section
echo '<br>'.$name.'<br>'.$email.'<br>'.$subject.'<br>'.$message;
/* Temporarily disabled for testing purposes
// Send email
if($emailC->send(false)){
// Redirect
return redirect()->to(base_url().'/contact')->with('success', true);
}else{
// Display error
throw new \CodeIgniter\Database\Exceptions\DatabaseException();
};
*/
}
}
}
Contact View
<div class="container">
<div class="row">
<div class="col">
<div class="alert alert-success align-center" id="message-alert" <?php if($success){echo 'style="display:block"';} ?>>Message successfully sent!</div>
</div>
</div>
<div class="row justify-content-center">
<div class="col-md-6">
<?php echo form_open('send_email', ['id'=>'contactForm'])?>
<div class="form-group">
<label for="name">Name</label>
<input name="name" type="text" class="form-control" id="name" aria-describedby="name" placeholder="Name" required>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('name')){echo $validation->getError('name');}?></p>
</div>
<div class="form-group">
<label for="email">E-Mail</label>
<input name="email" type="email" class="form-control" id="email" aria-describedby="email" placeholder="E-mail" required>
<small id="emailHelp" class="form-text">I'll never share your email with anyone else.</small>
<?php //echo $validation->email;?>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('email')){echo $validation->getError('email');}?></p>
</div>
<div class="form-group">
<label for="subject">Subject</label>
<input name="subject" type="text" class="form-control" id="subject" placeholder="Subject" required>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('subject')){echo $validation->getError('subject');}?></p>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea name="message" rows="5" class="form-control" id="message" placeholder="Type your message here." required></textarea>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('message')){echo $validation->getError('message');}?></p>
</div>
<button id="submitButton" type="submit" class="btn btn-primary g-recaptcha" data-sitekey="6Ldf07AZAAAAAAflQCaJcWgGFCWevCswpIrm0mJN" data-callback='onSubmit' data-action='submit'>Submit</button>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('captcha')){echo $validation->getError('captcha');}?></p>
<?php echo form_close()?>
</div>
</div>
</div>
<script>
function onSubmit(token) {
document.getElementById("contactForm").submit();
}
</script>
<script src="https://www.google.com/recaptcha/api.js"></script>
From my understanding of the way validation used to work in CodeIgniter, is that when you loaded your view after a form validation it would update the values with what was previously entered. This does not seem to be the case for CodeIgniter 4. I've also tried directly loading the views rather than calling the index function on validation fail. Still would not fill in the form values.
Now I could just pass these values to the index function via $data array. Which is the fix I'm going to use for now. This is more so a sanity check to see if there is something basic I'm missing or if I'm incorrectly using the validation format for CodeIgniter 4.
in CI4 you can use old() function to preserve the input value upon form validation:
View file:
<input type="tel" name="phone" value="<?= old('phone'); ?>">
In Controller you must use withInput() in the redirect() code:
$validation = \Config\Services::validation();
$request = \Config\Services::request();
// your input validation rules
$validation->setRules(...)
if($request->getMethod() == "post" && ! $validation->withRequest($request)->run()) {
return redirect()->back()->withInput()->with('error', $this->validation->getErrors());
} else {
// form validation success
}

404 NOT FOUND EDIT AND UPDATE LARAVEL 6

while passing variable in URL to edit and update a form it's returning only 404 not found , the tutorials did not help me , so this is my code :
controller : rendezv.php
public function editer ($id) {
$rdv= rendezvous::findOrFail('id');
return view ('/edit', ['modifier'=>$rdv]);
}
public function update(Request $request ,$id)
{
$this->validate($request, [
'email' => 'required' ,
'tel' => 'required'
]);
//modifier rendez vous
$editer=rendezvous::findOrFail('id');
$editer->Email = $request->input('email');
$editer->tel = $request->input('tel');
$editer-> save();
return redirect('/index');
}
and this this edit.blade.php
<form action="/update/{{$modifier->id}}" method="post" role="form" data-aos="fade-up">
#csrf
<input type="hidden" name="_method" value="PATCH" />
<input placeholder="{{$modifier->Email}}" type="email" class="form-control" name="email" id="email" data-msg="Please enter your name " />
<input placeholder="{{$modifier->Numéro_de_téléphone}} " type="text" class="form-control" name="tel" id="subject" data-rule="minlen:8" data-msg="Please enter at least 8 numbers" /> </i>
<div id="buttons">
<button type="submit" class="btn btn-primary"> modifier </button>
</div>
</form>
and finally route :
Route::get('/rendezvous_{ID}', 'doctor#rdv');
Route::post('/rdv','rendezv#rdv');
Route::post('/bienvenu','doctor#authentification')->name('aziz');
Route::get('/edit/{id}','rendezv#editer');
need yr help guys , and thank you
Please add the route for update
Route::patch('/update/{id}','rendezv#update');
You get 404 for both edit and update for findOrFail() method. You are passing string 'id' instead of $id.
In editer method please replace
$rdv= rendezvous::findOrFail('id');
with
$rdv= rendezvous::findOrFail($id);
In update method please replace
$editer=rendezvous::findOrFail('id');
With
$editer=rendezvous::findOrFail($id);
Furthermore, findOrFail() method will return 404 if no data is found with the given $id
You route /update/{{$modifier->id}} doesn't exist, you need to declare it in you router file:
Route::post('/update/{id}','rendezv#update');
Take a look at the Resource Controllers
What you are looking for is a Route::post('/edit/{id}','rendezv#update'); or put or patch
You are missing a post route:
Route::post('/edit/{id}','rendezv#update');

Trying to get property of non-object while reset user password

I am trying to reset the password but I am getting the error message "Trying to get property of non-object".
I have also attached the screen shot of my error please have a look at it.
My Controller for resetting the password:
class ResetPasswordController extends Controller
{
protected $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function showResetForm(Request $request, $token = null)
{
return view('auth.passwords.reset')->with(
['token' => $token, 'email' => $request->email]
);
}
public function reset(Request $request)
{
try {
$password = $this->user->where('id', Auth::user()->id)->value('password');
if(Hash::check($request->input('current_password'),$password)) {
$this->user->where('id', Auth::user()->id)->update(['password' => bcrypt($request->input('new_password'))]);
$token = $request->header('Authorization');
JWT::invalidate($token);
Auth::logout();
return response(['status' => true, 'message' => 'Password changed successfully'], 200);
} else {
return response(['status' => false, 'message' => 'The Current Password is invalid.'], 200);
}
} catch (\Exception $ex) {
return response(['status' => false, 'message' => $ex->getMessage()], 500);
}
}
}
My Routes configuration:
\Illuminate\Support\Facades\Auth::routes();
Route::get('password/reset/{token}', 'Auth\ResetPasswordController#showResetForm');
Route::post('password/reset', 'Auth\ResetPasswordController#reset')->name('password.request');
My View template:
<form action="{{ route('password.request') }}" method="post">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label for="login-form-email">Current Password</label>
<input type="password" class="form-control" name="current_password" id="login-form-password" tabindex="2" placeholder="Current Password" tabindex="4">
</div>
<div class="form-group">
<label for="login-form-password">New password</label>
<input type="password" class="form-control" name="new_password" id="login-form-password" tabindex="2" placeholder="New Password" tabindex="4">
</div><!-- /.form-group -->
<div class="form-group">
<label for="login-form-password-retype">Confirm new password</label>
<input type="password" class="form-control" name="new_password_confirmation" id="login-form-password-retype" tabindex="3" placeholder="Confirm password">
</div><!-- /.form-group -->
<div class="form-group">
<input type="submit" class="btn btn-primary pull-right" name="reset-confirm" id="reset-confirm" tabindex="4" value="Reset Password">
</div>
</form>
How can I find a solution based on this code and error message?
User doesn't need to be a member
Your first problem is here:
public function __construct(User $user)
You're injecting a user, without it knowing what user to use, unless this is coming from middleware. So the constructor shouldn't take a user, nor do you need to protected member. If you really want it as a protected member you could do the following:
public function __construct()
{
$this->user = Auth::user();
}
But since you have Auth::user(), you don't need it as a member.
where on a Model is Static
You have
$this->user->where('id', Auth::user()->id)->value('password')
Model's where function is a static function you shouldn't call it on an individual object. Instead you shoud call it using the scoping operator (::). Most versions of PHP should error out at that point. The correct way to get the current user's password hash from the database is:
$hash = Auth::user()->password;
If you had an id, you could:
$hash = User::where('id','=',$userId)->get()->password;
If you kept the user as a member (against the recommendation) but did it as in the above section of this answer, you could:
$hash = $this->user->password
Why?
Lastly, the Auth module from Laravel in modern versions already takes care of this for you in app\Http\Controllers\Auth. Why are reinventing the wheel?

Html disappear after using form_error function in codeigniter

I am trying to add the form error messages in my html form. Problem is there in first view. In user function html is disappear from where I start to use form_error(). My Original form design is like this: my original form
but after adding the form_error under the first input: my form error image
Here is my html code
<div class="form-group">
<label for="name"><i class="zmdi zmdi-account material-icons-name"></i></label>
<input type="text" name="username" id="name" placeholder="Your Name" />
<?php echo form_error('username','<p class="p_errror" id="name_error_p">','</p>') ?>
</div>
<div class="form-group">
<label for="email"><i class="zmdi zmdi-email"></i></label>
<input type="text" name="email" id="email" placeholder="Your Email"/>
<?php echo form_error('email','<p class="p_errror" id="name_error_p">','</p>') ?>
</div>
Here is my controller
<?php
class Register extends CI_Controller
{
public function user()
{
$this->load->view('files/registration/signup');
}
public function login()
{
$this->load->view('files/registration/login');
}
public function description()
{
$this->load->view('files/registration/description');
}
public function registerMe()
{
$this->load->helper('form','url');
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required|alpha|max_length[15]');
$this->form_validation->set_rules('pass', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
$this->form_validation->set_rules('re_pass', 'Confirm Password', 'required|matches[pass]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if ($this->form_validation->run()===FALSE) {
$this->load->view('files/registration/signup');
}
else
{
$this->load->model('RegisterUser');
$this->RegisterUser->registerme($_POST);
}
}
}
?>
you need to load the form helper in signup function too. form_error is a function in form_helper. (this is required for other functions with a form view too)
public function user()
{
$this->load->helper('form');
$this->load->view('files/registration/signup');
}
html is disappeared because there was php error. check your error log when this happens or change codeigniter environment to development in index.php

codeigniter setting up a password!

I try to set up a password in a codeigniter form...
Everything seems ok to my eyes but no matter which password I use the form is still submitted...
here is the code in the controler:
class MyBlog extends Controller{
function MyBlog(){
parent::Controller();
$this->load->helper(array('url','form','html')); //here we load some classes that we use
$this->load->scaffolding('entries'); //scaffolfing is a feature that lets you add or remove elements from the database
$this->load->scaffolding('comments');
$this->load->library('form_validation');//load validation class used to validate our forms...
}
function index(){
$data['title'] = "My Blog Title"; //the title of my blog
$data['query'] = $this->db->get('entries'); //here we make a small query to entries table
$this->load->view('myBlog_view', $data); ///load all data variables on myBlog_view.php
//this is also for the form validation
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('body', 'Body', 'required');
$this->form_validation->set_rules('author', 'Author', 'required');
$this->form_validation->set_rules('pass', 'Pass', 'callback_pass_check');
function pass_check($str) {
if ($str == 'baywatch'){
return TRUE;
}
else{
return FALSE;
}
}
if ($this->form_validation->run() == TRUE)
{
$this->myBlog_insert();
//$this->load->view('formSuccess_view');
}
}
function myBlog_insert(){
$insert = array( 'title' => $_POST['title'],
'body' => $_POST['body'],
'author' => $_POST['author']
);
$this->db->insert('entries',$insert);
redirect('myBlog/');
}
}
and this is my form:
<div class="theForm">
<?php echo $this->form_validation->error_string; ?>
<?php echo validation_errors(); ?>
<?php echo form_open('myBlog'); ?>
<label for="title">Title:</label>
<input type='text' name="title" size="40" id="title" />
<p>
<label for="body">Body:</label>
<textarea name="body" rows = "10" cols="60" id="body"></textarea>
</p>
<p>
<label for="author">Author:</label>
<input type="text" name="author" size="40" id="author"/>
</p>
<p>
<label for="pass">Password:</label>
<input type="password" name="pass" size="38" id="pass"/>
</p>
<p><input type="submit" value="Submit New Post"/></p>
</form>
</div>
</body>
</html>
any ideas?
thanks in advance
<label for="pass">Password:</label>
<input type="text" name="pass" size="38" id="author"/>
The input type is text no password, the id='pass'.
Ok, a couple of things first:
1) id's should be unique. ie your author field and your password field shouldn't have the same id.
2) password fileds should use the type "password" not "text".
I think the reason you're having problems is with your callback function pass_check(). Try changing your function to:
function pass_check($pass)
{
if($pass !== 'baywatch')
{
return FALSE;
}
By the way, scaffolding has now been deprecated. Can I suggest you look into using models and the active record class as a way of interacting with your db? Also, this really isn't a very secure way of handling passwords. Have a look at some of the CI authentication libraries and see if you can implement one of them.
Ok guys...I found what the problem was...function pass_check was declared inside index()...and for some reason it needs to be outside as a method of the class...Hope this will help others... I give some ups for all the suggestions...

Categories