Login Throttling Function with Active Record - codeigniter

I have a function that I found that was wrote to use PDO, I modified it to use codeigniters active record db class. Everything work EXCEPT when I place the code within a function like so:
function login_attempt_count() {
$seconds = 10;
// First we delete old attempts from the table
$oldest1 = strtotime(date('Y-m-d H:i:s').' - '.$seconds.' seconds');
$oldest2 = date('Y-m-d H:i:s',$oldest1);
$del_data = $oldest2;
$this->db->where('when <', $del_data);
$this->db->delete('Login_Attempts');
// Next we insert this attempt into the table
$data = array(
'ip' => $_SERVER['REMOTE_ADDR'],
'when' => date("Y-m-d H:i:s"));
$this->db->insert('Login_Attempts', $data);
// Finally we count the number of recent attempts from this ip address
$count = 'SELECT count(*) as number FROM Login_Attempts WHERE ip = ?';
$num = $this->db->query($count, $_SERVER['REMOTE_ADDR']);
if ($num->num_rows() > 0){
foreach($num->result() as $attempt){
$attempts = $attempt->number;
return $attempts;
}
}
}
using it like this:
$max_attempts = 3;
if(login_attempt_count() <= $max_attempts) {
echo 'login';
}else{
echo 'To many attempts';
}
or this:
$a = login_attempt_count();
Causes the rest of the page to not load. So this indicates an error.
Again if I use the code within the function, outside the function, it works as expected.
Or if there is a completely better and more secure method that I should be using I am open for suggestions. Thanks!

Ok here I am answering my own question. ;) The function works fine! However, testing it in a view causes an error? After placing the function within my model and calling the function within my controller works great. Using it like so:
class Auth extends CI_Controller{
function login(){
$max_attempts = 3;
if($this->auth_model->login_attempt_count() <= $max_attempts) {
//Do something
}else{
//Something else
}
}//End Function
}//End Class

Related

Laravel Multiple Edit/Upload File

I want to make my code more efficient in my Controller. This code is about to update file in the database and then delete the file were chosen, rather than use if-condition i will use switch statement and then call the updateFile function for each case of file name. But i have problem on my switch statement, it supposed to run for each case but doesn't.
private function updateFile($strFileName, $oldFileName){
if($request->file($strFileName)){
if($request->$oldFIleName){
Storage::delete($request->$oldFIleName);
}
$validatedData[$strFileName] = $request->file($strFileName)->store('post-files');
}
}
public function update(Request $request, Task $task)
{
//storing files request
$rules = [
'file_jamlak' => 'mimes:pdf,png,jpg|file|max:4096',
'file_kontrak' => 'mimes:pdf,png,jpg|file|max:4096',
'file_jamuk' => 'mimes:pdf,png,jpg|file|max:4096']
//validate rules in to new variable
$validatedData = $request->validate($rules);
//the switch
$file_name = $request->file();
switch($file_name){
case 'file_jamlak' : $this->updateFile('file_jamlak', 'oldJamlak');
}
//condition
//jamlak
if($request->file('file_jamlak')){
if($request->oldJamlak){
Storage::delete($request->oldJamlak);
// return $request->oldJamlak;
}
$validatedData['file_jamlak'] = $request->file('file_jamlak')->store('post-files');
$validatedData['jamlak'] = 1;
}
//kontrak
if($request->file('file_kontrak')){
if($request->oldKontrak){
Storage::delete($request->oldKontrak);
}
$validatedData['file_kontrak'] = $request->file('file_kontrak')->store('post-files');
$validatedData['kontrak'] = 1;
}
//add user id
$validatedData['user_id'] = auth()->user()->id;
//update eloquent
Task::where('id', $task->id)
->update($validatedData);
//dd($file_name);
return redirect('/admin/tasks')->with('success', 'New post has been updated!');
}
i think i made mistake on the $file_name, that it supposed to store file name but doesn't work. Please help me
Make sure you've file name in your case which you are checking against:
// ...
//the switch
$file_name = $request->file();
switch($file_name){
// make sure this name matches the name of the file you are submitting
// from the form on front end to be able to fall into this case
case 'file_jamlak' : $this->updateFile('file_jamlak', 'oldJamlak');
// ...

Stuck at Error = Method Illuminate\Database\Eloquent\Collection::save does not exist

Trying to save data while open page but stuck at error :
"Method Illuminate\Database\Eloquent\Collection::save does not exist."
I have 2 database :
Buffalodata
Buffalomilkrecord
From 2nd table i need to get the avg of totalmilk and update the same to main database (1). This help me to show updated avgmilk data on dashboard front page.
Route:
Route:: get('buffalo-details', 'App\Http\Controllers\BuffalodataController#buffalodetails');
BuffalodataController Controller :
public function buffalodetails()
{
$buffalidforavgmilk = Buffalodata::groupBy('buffaloID')->get('buffaloID')->pluck('buffaloID')->toArray();
foreach ($buffalidforavgmilk as $id )
{
$milkperid = Buffalomilkrecord::where('buffaloID', $id)->sum('totalmilk');
$avgbuffalocount = Buffalomilkrecord::where('buffaloID',$id)->count();
$getavg = $milkperid / $avgbuffalocount;
$data = Buffalodata::find($buffalidforavgmilk);
$data->avgmilk = ($getavg);
$data->save ();
// dump([$milkperid,$avgbuffalocount,$getavg,$data,$id]);
}
return view ('pages.Buffalo.BuffaloDetails',[---------]);
}
Thanks again in Advance
When you pass an Array to ::find(), it returns a Collection, which doesn't have a save() method. This is your code:
// This is an Array of `buffaloID` values
$buffalidforavgmilk = Buffalodata::groupBy('buffaloID')->get('buffaloID')->pluck('buffaloID')->toArray();
...
// `$data` is now a `Collection` of `Buffalodata` instances
$data = Buffalodata::find($buffalidforavgmilk);
// This now fails, as `Collection` doesn't have a `save()` method
$data->save();
You can rewrite your code as follows:
Buffalodata::whereIn('buffaloID', $buffalidforavgmilk)->update(['avgmilk' => $getavg]);
This will update all records in a single call. If you want to iterate, that's an option too:
$data = Buffalodata::find($buffalidforavgmilk);
foreach ($data as $record) {
$record->avgmilk = $getavg;
$record->save();
}
Or, since you have $id already:
$record = Buffalodata::find($id);
$record->avgmilk = $getavg;
$record->save();

codeigniter ftp get filesize

How can i get remote file's file size with codeigniter?
after making a connection , i want to get properties.xml file's size. in ordinery ftp i would get it with no problem but since i start using codeigniter it is kinda difficult.
this is in procedurel php ;
$remote_filesize = ftp_size($conn_id, "properties.xml");
but how can i do it in codeigniter?
if($this->ftp->connect($config))
{
/*here some magic code*/
}
this a small example
Controller_ftp.php
class Controller_ftp extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->library('ftp');
}
publilc function get_ftp_info(){
$config['hostname'] = 'ftp.example.com';
$config['username'] = 'your-username';
$config['password'] = 'your-password';
$config['debug'] = TRUE;
foreach($this->ftp->list_files('/public_html/') as $item){
$size = filesize($item);
echo "name => $item - size => $size - etc <br>";
clearstatcache();
}
}
}
If you want to use $this->ftp->file_size($file), you need to extend ftp library and create the function retunring filesize($item);
ok i went to library->ftp.php and basically added a function
public function get_conn_id()
{ return $this->conn_id;}
and later all i need to do was calling the function like this
$conn_id = $this->ftp->get_conn_id();
$remote_filesize = ftp_size($conn_id, "properties.xml");

codeigniter call to a member function row() on a non-object

I've searched the ends of the earth and back for this solution, and for everyone else, the fix was to autoload the database class in autoload.php. However, I am already doing this, so I don't know where else to go with it.
Controller:
class Login extends CI_Controller{
function validate_credentials(){
$this->load->model('membership_model');
// call the member function from membership_model.php
$q = $this->membership_model->validate();
if($q){
// user info is valid
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('site/members_area');
}else{
$this->index();
}
}
}
Model:
class Membership_model extends CI_Model{
function validate(){
// this method is called from the login.php controller
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', md5($this->input->post('password')));
$q = $this->db->get('members');
if($q->num_rows == 1){
return true;
}
return false;
}
}
Any help on this please, I'm going round in circles with this
My next thought is that php.ini needs configuring on my host server, to load the mysql modules - but I would very surprised by this?
Just to clarify - the line:
if($q->num_rows)
Is the problem, saying that I am trying to reference a property of a non object
Actually
if($q->num_rows)
should be
if($q->num_rows()) // It returns the number of rows returned by the query.
So you can use
if($q->num_rows()) // In this case it'll be evaluated true if rows grater than 0
{
// code when rows returned
}
num_rows is a function.
if ($query->num_rows() > 0) {
}
So you need
if($q->num_rows() > 0) {
return true;
}
Solved - I hadn't assigned a User to the database, therefore couldn't access it.
Relief

Form validation with custom callback function

I created a "callback" function to check if the username exists in the DB.
I have multiple rules for the "username" field, but the only thing that work is my callback function. It refuses to check against the other rules. I tried leaving the field empty, and the "required" rule never kicked in.
Controller:
account.php
function register() {
$this->load->library('validation');
$fields['username'] = "trim|required|callback_username_check";
etc ...
etc ...
$this->validation->set_rules($fields);
if ($this->validation->run()) {
$records = array();
$records['username'] = $this->validation->username;
etc ...
etc ...
$data = $this->account_model->registerNewAccount($records);
}
$this->load->view('register_view');
}
function username_check($username) {
$m = new Mongo();
$collection = $m->selectDB( DBNAME )->selectCollection( TABLE );
$data = $collection->count(array("username" => $username) );
if($data == 1) {
$this->validation->set_message('username_check', '%s is already taken!');
return false;
} else {
return true;
}
}
Try using the new form_validation class here:
http://ellislab.com/codeigniter/user_guide/libraries/form_validation.html
I believe there was a bug about it.

Resources