Quantcast
Channel: CodeIgniter Forums - All Forums
Viewing all 14108 articles
Browse latest View live

Maximum call stack size exceeded in development enviroment

$
0
0
Hello,

I am playing around with CI4, I have a very simple page that doesn't have any JS on it.

But if change the environment to development I start getting these errors:

[Image: Screenshot-2020-11-26-at-23-42-04.png]

[Image: Screenshot-2020-11-26-at-23-42-15.png]


I tried removing the catch and emptying the writable folder. 

It's so annoying, page is only 5 lines of HTML code and no JS, where is the problem?

Regards

localhost send an invalid response

$
0
0
hello there,

im just learning codeigniter 4 from youtube "web programming unpas". so im followed his course to create form with post method to insert data.
after insert the data succesfully, it will redirect to the index file. then, after i tried to insert data, the data its inserted successfully, but cannot redirect and showing error

"localhost send an invalid response"

here the code
route.php
Code:
$routes->get('/', 'pages::index');

$routes->get('/komik/create', 'komik::create');
$routes->get('/komik/(:segment)', 'komik::detail/$1');

controller/komik.php
Code:
<?php
namespace App\Controllers;

use App\Models\komikmodel;

class komik extends BaseController

    {
         protected $komikmodel;
   
         public function __construct()
         {
              $this->komikmodel = new komikmodel();
         }
   
   
         public function index()
         {
                $data = [
                   'title' => 'Daftar Komik' ,
                   'komik' => $this->komikmodel->getkomik()
              
              ];
              return view('komik/index', $data);
         }
   
         public function detail($slug)
         {
              $data = [
                   'title' => 'Detail Komik',
                   'komik' => $this->komikmodel->getkomik($slug)
              ];
   
              if(empty($data['komik']))
              {
                   throw new \CodeIgniter\Exceptions\PageNotFoundException('Judul Komik '. $slug. 'Tidak Ditemukan');
              }
   
              return view('komik/detail', $data);
         }
   
         public function create()
         {
              $data = [
                   'title' => 'Form Tambah Data Komik'
              ];
   
              return view('/komik/create', $data);
         }
   
         public function save()
         {
              $slug = url_title($this->request->getVar('judul'), '-', true);
   
              $this->komikmodel->save([
                   'judul' => $this->request->getVar('judul'),
                   'slug' => $slug,
                   'penulis' => $this->request->getVar('penulis'),
                   'penerbit' => $this->request->getVar('penerbit'),
                   'sampul' => $this->request->getVar('sampul')
              ]);
   
              session()->setFlashData('pesan', 'Data berhasil di tambahkan!');
   
              return redirect()->to('/komik');
         }
    }

any suggestion will be appreciated
thanks

submit on a form

$
0
0
I have an email that I am sending to users. In it a user clicks on a link which brings them to http://localhost/index.php/Configure/MyFormEmployee which is a function in my controller that displays a survey.  They fill out the form and hit "submit" which brings them to http://localhost/index.php/Configure/survey_results which is another function in my controller. In survey_results() I will total up the survey and write the results to a mysql table. Ignore the "localhost" implications since that is just for testing. 

But what happens if the user of the CI application is no longer running the application? Since this survey invitation is sent via email and the receiver has 48 hours to fill out a survey there is a very good chance that they will no longer be running the application. Will the survey results function still run? 

Download Persian translation of CodeIgniter 4 documentation

$
0
0
Download Persian translation of CodeIgniter 4 documentation
Hello.
CodeIgniter is an excellent framework.
I have Ci4 translated by Google TranslateSadthe first 5 chapters to the end of General Topix.)
Translated by (Google Translate) and edited by me.

I will translate other chapters.

Download link:
https://webarts.ir/download/368/

دانلود ترجمه فارسی مستندات کدایگنایتر 4

Download Persian/Farsi CI4 Documentation

SQL : join with tables with same fields name (eg primary id) return invalid results

$
0
0
Hi,

I noticed that if I build a query with 2 tables having the same name for primary key (and I guess this will be the case with any other field), the result is invalid as the id key in the resulting array contains only the id of the joined table.

This is for example the case in the documentation :


PHP Code:
$builder->db->table('blog');
$builder->select('*');
$builder->join('comments''comments.id = blogs.id');
$query $builder->get();

// Produces:
// SELECT * FROM blogs JOIN comments ON comments.id = blogs.id 



We should have 2 id keys (I know this isn't possible in php, but the name of the result array key should be blogs.id and comments.id)


Sincerly,

Fred

Multiple Class Instances vs Function Call

$
0
0
I have been pondering the wisdom of my methodology for a while and thought let's hear what the community has to say. I started this methodology using CI 3 and have now ported the principle to my CI4 applications
Scenario:
Developing a CRM type system and when designing the layout of the User Profile page I have to display various sections containing information from different parts of the system e.g. On the transactions tab we have two columns (1) table of all Invoices (2) table of Orders. Tab Support: Shows Tickets. Tab Technical: shows tables of Login History, Emails from the system etc.
Method 1:
At the start of the view create instances of all the Models that will be used to obtain the data e.g. InvoicesModel, OrderModel, TicketsModel etc. Then call the methods needed as and when required. E.g
Code:
<div>
<?= $modelInvoices->displayTable( $clientId); ?>
</div>
Rinse and repeat for all the information blocks. All the variables gets released once the view has been processed.

Method 2 (which I have been using):
I have created a helper function file which is loaded in BaseController. In this Wrapper Helper I have defined numerous functions that all they do is get an instance of a class and execute a method and return the result. To use the example above i Wrapper Helper:
PHP Code:
function getInvoiceTable$clientId) {
$model = new \App\Models\InvoicesModel();
return 
$model->displayInvoices$clientId);

In the view the code would look something like:
Code:
<div>
<?= getInvoiceTable( $clientId ) ?>
</div>

My thinking was that using the function call the model instance is created, used and the memory released whereas with method one the memory for all the class instances are only released on completion of the view.

The reason that I brought this up that in one app the profile view is now opening 7 model classes and that could increase going forward.

All thoughts and input will be appreciated.

Surprised to see codeigniter 3.x running successfull with PHP 8.0 as well.

$
0
0
Codeigniter 3.x running successfully with PHP 8.0 as well.
Without any changes its working very well.
Great news guys. Smile

DATABASE ERROR

$
0
0
I got this error when installing a website:

Error Number: 1054
Unknown column 'status' in 'where clause'
SELECT * FROM `web_slider` WHERE `status` = 1 ORDER BY `slider_id` ASC
Filename: models/website/Web_model.php
Line Number: 95

This is the code:

PHP Code:
public function active_slider()
    {
        return 
$this->db->select('*')
            ->
from('web_slider')
            ->
where('status'1)
            ->
order_by('slider_id''asc')
            ->
get()
            ->
result(); 


Someone should please assist me. thank you

.png   Screen Shot 2020-11-29 at 2.06.55 AM.png (Size: 27.64 KB / Downloads: 0)

Filter's dont work

$
0
0
HI , i try to implement a filter to control if admin is authenticated :

Code:
<?php namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;

class AdminFiltersAuth implements FilterInterface
{
    /**
     * Do whatever processing this filter needs to do.
     * By default it should not return anything during
     * normal execution. However, when an abnormal state
     * is found, it should return an instance of
     * CodeIgniter\HTTP\Response. If it does, script
     * execution will end and that Response will be
     * sent back to the client, allowing for error pages,
     * redirects, etc.
     *
     * @param \CodeIgniter\HTTP\RequestInterface $request
     * @param array|null                         $params
     *
     * @return mixed
     */
    public function before(RequestInterface $request, $params = null)
    {
        // if no user is logged in then send them to the login form
        if (!session()->get('admin_id'))
        {           
            session()->set('redirect_url', current_url());
           
            return redirect()->to( base_url().'/admin/login');
        }
    }

    //--------------------------------------------------------------------

    /**
     * Allows After filters to inspect and modify the response
     * object as needed. This method does not allow any way
     * to stop execution of other after filters, short of
     * throwing an Exception or Error.
     *
     * @param \CodeIgniter\HTTP\RequestInterface  $request
     * @param \CodeIgniter\HTTP\ResponseInterface $response
     * @param array|null                          $arguments
     *
     * @return void
     */
    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {

    }

    //--------------------------------------------------------------------

}   // End of YourFilterName Class.


i want filter every controller's method except login to prevent loop redirect

in Config/Filter this is my code:

Code:
<?php namespace Config;

use CodeIgniter\Config\BaseConfig;

class Filters extends BaseConfig
{
    // Makes reading things below nicer,
    // and simpler to change out script that's used.
    public $aliases = [
        'csrf'     => \CodeIgniter\Filters\CSRF::class,
        'toolbar'  => \CodeIgniter\Filters\DebugToolbar::class,
        'honeypot' => \CodeIgniter\Filters\Honeypot::class,
        'adminFiltersAuth' => \App\Filters\AdminFiltersAuth::class,
        'adminFiltersNoAuth' => \App\Filters\AdminFiltersNoAuth::class,
        'showSessionFilter' => \App\Filters\ShowSessionFilter::class,
    ];

    // Always applied before every request
    public $globals = [
        'before' => [
            //'showSessionFilter'
            //'honeypot'
            // 'csrf',
        ],
        'after'  => [
            'toolbar',
            //'honeypot'
        ],
    ];

    // Works on all of a particular HTTP method
    // (GET, POST, etc) as BEFORE filters only
    //     like: 'post' => ['CSRF', 'throttle'],
    public $methods = [];

    // List filter aliases and any before/after uri patterns
    // that they should run on, like:
    //    'isLoggedIn' => ['before' => ['account/*', 'profiles/*']],
    public $filters = [

        'adminFiltersAuth' => ['before' => ['admin/*'] ],
        'adminFiltersAuth' => ['except' => ['admin/login']],
        'adminFiltersNoAuth' => ['before' => ['admin/login']],



    ];
}

but if i go to ade admin/changeEmail if the admin are not logged in mut im not redirected . 
in route if i insert this code :

Code:
$routes->add('admin/changeEmail', 'Admin::changeEmail',['filter'=>'adminFiltersAuth']);

it works fine  but in some controller i want to filter every method and is too boring write a route with filter for every metods
Why ?

ci3 cors doesn't works

$
0
0
Hallo i have a tasks from college to create elearning (me as backend) but i have problem when i deploy it to vps it's always getting error that said 'CORS NOT ALLOWED'.

Im using:
  • Codeigniter3
  • Library ci rest server (criskagruice)
  • JWT
  • NGINX
  • simple login xhr with github.io
My structure of code is ALL ENDPOINT/Class (.php) extends to Token.php extends to REST_Controller.php (library).

Here are ma code:

Login page (github.io)

Code:
  let xhr = new XMLHttpRequest();
  xhr.open('POST', 'https://IP_VPS/elearning/auth/login');
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.onreadystatechange = function() {
    if(this.readyState == 4 && this.status == 200) {
      console.log(this.response);
    }
  }
  xhr.send('email='+email.value+'&password='+password.value);


Token.php (child of REST_Controller)

Code:
<?php
// load library rest server
use Restserver\Libraries\REST_Controller;
require APPPATH . 'libraries/REST_Controller.php';
require APPPATH . 'libraries/Format.php';

// load library rest server
use \Firebase\JWT\JWT;
require APPPATH . 'libraries/JWT.php';
require APPPATH . 'libraries/BeforeValidException.php';
require APPPATH . 'libraries/ExpiredException.php';
require APPPATH . 'libraries/SignatureInvalidException.php';

defined('BASEPATH') OR exit('No direct script access allowed');

class Token extends REST_Controller {

  private $_secretkey = 'elearning';
  private $_token;

  public function __construct(){
    header("Access-Control-Allow-Origin: *");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');
    parent::__construct();
    $this->load->model('m_users', 'user');
  }
......................................................

} ?>


Auth.php (child of Token.php)

Code:
<?php
require APPPATH . 'controllers/api/Token.php';

defined('BASEPATH') OR exit('No direct script access allowed');

class Auth extends Token {

  public function __construct() {
    parent::__construct();
    $this->load->library('form_validation');
  }

  public function login_post() {
    // terima data dari form
    $email    = $this->post('email');
    $password = $this->post('password');

    $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
    $this->form_validation->set_rules('password', 'Password', 'required');

    // form validation false akan merespon input form yang false
    if (!$this->form_validation->run()) {
      $form_error = $this->form_validation->error_array();
      $this->response([
        'status'  => FALSE,
        'message' => 'form tidak lengkap',
        'error'   => ['form_error' => $form_error]
      ], 404);
    }



    //  -------- AKAN DIEKSEKUSI JIKA FORM INPUT LENGKAP ------

    // cek apakah user ada pada database
    $user_detail = $this->user->getUser($email);

    if (!$user_detail) {
      $this->response([
        'status' => FALSE,
        'message' => 'Email/Password Salah'
      ], 404);
    }

    // response 404 jika user tidak ada
    $hash_password = $user_detail['password'];

    if ( !password_verify($password, $hash_password) ) {
      $this->response([
          'status' => FALSE,
          'message' => 'Email/Password Salah',
      ], 404);
    }

    // menyiapkan token
    $token = parent::generateToken($user_detail);

    // menyapkan response json
    $response = [
      'status'  => TRUE,
      'message' => 'berhasil login',
      'data'    => [
                    'name' => $user_detail['name'],
                    'email' => $user_detail['email'],
                    'user_role' => $user_detail['type'],
                    'token' => $token
                  ]
    ];

    // response 200 user berhasil masuk
    $this->response($response, 200);
  }

}
?>


/etc/nginx/sites-available/default



Code:
location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        #try_files $uri $uri/ =404;

        if ($request_method = 'OPTIONS') {
    add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        #
        # Custom headers and headers various browsers *should* be OK with but aren't
        #
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        #
        # Tell client that this pre-flight info is valid for 20 days
        #
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain; charset=utf-8';
        add_header 'Content-Length' 0;
        return 204;
     }
     if ($request_method = 'POST') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
     }
     if ($request_method = 'GET') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
     }
    }

    # pass PHP scripts to FastCGI server
    #
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
    #
    #    # With php-fpm (or other unix sockets):
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    #    # With php-cgi (or other tcp sockets):
    #    fastcgi_pass 127.0.0.1:9000;
    }

    # codeigniter elearning
    location /elearning {
        try_files $uri $uri/ /elearning/index.php;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny all;
    }

Im actually super new at creating API & deploying and don't know what should i do now. In these code above which is wrong ? Thanks Anyway Smile Smile

codeigniter4 language pack updated

[HELP WANTED] Update language strings to the latest develop

$
0
0
We need all the help we can get in updating the language packs in the translations repo to be in sync with the main repo just in time before the next release happening within the next days.

If you are the maintainer of the locale or is someone who is fluent in that locale, your help is needed.

Please head over to the CodeIgniter4 Translations repo on how you can contribute.

Thank you.

CodeIgniter 3 routes don't work in HTTPS

$
0
0
In my work we are migrating some websites to HTTPS, but the routes have stopped working under HTTPS and the server returns error 404, they are just putting the /index.php/ and under HTTP they have been working correctly.
I've been searching but nothing I've found works

This is my config.php:

Code:
$config['base_url'] = 'https://myweb.es';
$config['index_page'] = '';
$config['uri_protocol']    = 'REQUEST_URI';


And this the .htaccess:

Code:
Options FollowSymLinks
<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
    ErrorDocument 404 /index.php
</IfModule>

Thank you in advance

Class not found Error, problem with namespaces

$
0
0
I'm new to Codeigniter 4 and am struggling with namespaces. I tried to create a helper php2jquery.php in App/Helpers I cannot load it the way I try it. This is wat I have now.
PHP Code:
<?php namespace App\Controllers;
use 
App\Helpers\php2jquery;
class 
Test extends BaseController
{

    public function 
index()
    {
        
        
$param “”//Doesn’t matter here ;
        
        
$jqueryparam = New php2jquery();
    
        
$data[‘jqueryobject’] = $jqueryparam->php_array_to_jquery_param($param4"new FWDRAP""FWDRAPUtils.onReady(function(){" );
        
        
$data['base'] = config('App')->baseURL;
        return 
view('test_message',$data);
    }

    
//--------------------------------------------------------------------

}

————
File
App/Helpers/php2jquery.php  (Also tried App/Helpers/php2jquery_helper.php
__________
<?php
    
class php2jquery
    
{
        
        function 
php_array_to_jquery_param($param,$indent=0$object=""$wrapfunction=""){
            Return (
“this is a test”);
        }


Now, when I run it I get "Error: Class App\Helpers\php2jquery not found" I tried adding _helper tot the name and call it with and without it, but no luck. Can somebody tell me what is wrong? Thank you

Suggestion for extension of controller

$
0
0
Hello guys.

I need some advice on CI4. In ci3 I extended the controller with the MY_controller like this:
PHP Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');


 
class 
MY_Controller extends CI_Controller
{
  function __construct()
  {
    parent::__construct();

  }
}

class 
Guest_Controller extends MY_Controller        //Controller for Not Logged (free)
{
  function __construct()
  {
    parent::__construct();

  }
}

class 
Logged_Controller extends MY_Controller        //Controller for ALL Logged
{
  function __construct()
  {
    parent::__construct();
    if (!$this->ion_auth->logged_in())
        {
            
            redirect
('auth/login');
        }
  }
}

class 
Admin_Controller extends MY_Controller        //Controller for Admin
{
  function __construct()
  {
    parent::__construct();
    if (!$this->ion_auth->logged_in())
        {
            
            redirect
('auth/login');
        }
        else
            {
            if(!$this->ion_auth->is_admin())
                    {
                        $this->session->set_flashdata('flashError''This page is only for ADMIN');
                        redirect('example_logged');
                    }
            }
    }
  

so in each controller that i created, I extended the class I needed (adminController, LoggedController etc)

How can I get the same result with the BaseController? What class do I extend in my controllers, depending on whether they are admin, logged etc?

Thanks to all

Validation uploaded files not work with redirect back?

$
0
0
I've tried to validate the input of a form then use redirect()->back() but the validator doesn't work validating the upload file. I've checked with getErrors() function but its empty.
How to solve that issue? I really appreciate for your help and response.

PHP Code:
public function index($id_customer)
    {
        $session session();
        $data['customer'] = $this->CustomerModel->getCustomerById($id_customer);
        $data['validation'] = \Config\Services::validation();

        return view('form'$data);
    }

public function 
add($id_customer)
    {
        $session session();

        $rules = [
             // I don't know why if I comment 'images' rule the validation goes well
            'images' => [
                'label' => 'Images',
                'rules' => 'uploaded[images.0]|max_size[images,4096]|is_image[images]|mime_in[images,image/gif,image/jpeg,image/png]',
                'errors' => [
                    'uploaded' => '{field} field is required',
                    'is_image' => 'Uploaded files are not Image files.',
                    'max_size' => 'Allowed maximum size is 4MB',
                    'mime_in' => 'The Image type is not allowed. Allowed types : gif, jpeg, png'
                ],
            ],
            'notes' => [
                'label' => 'Notes',
                'rules' => 'required',
                'errors' => [
                    'required' => '{field} field is required'
                ]
            ],
        ];

        if (!$this->validate($rules)) {
            // Validator with rules
            $validation = \Config\Services::validation();
            return redirect()->back()->withInput()->with('validation'$validation); //redirect to Index function
        
    

can lock up environment at will

$
0
0
I have found that in using Fusion Auth, if I try to reregister  a user already registered the browser locks up. I can close the browser and try to start the program again but it is still locked. The line below is the line in index.php that dies. 

define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');

Any idea how to solve this or is this a fusion auth question?

Connect to DB in external Library (CI 4)

$
0
0
I have my custom library in Codeigniter 4:

<?php namespace App\Libraries;

class MyUrlang {

function __construct() {

//$conn = \Config\Database::connect();
}

public function get_url_lang($page = '', $var = ''){

$conn = db_connect();

$sql = "SELECT * FROM tab1 LIMIT 1";

$result = mysqli_query($conn, $sql);

$row = mysqli_fetch_assoc($result);

etc etc
}
}

In can't connect using mysqli_query... i receive this error: mysqli_query() expects parameter 1 to be mysqli, object given

I user connection in every my controller and model with no problem.

Which is the better way?

Migration runs successfully but not creating tables

$
0
0
Hi everyone,
I'm having problem with migration, migration runs successfully on CLI but it doesn't create any table except migration table which contains migration related detail. Any help?
pls find the images below:

[Image: cz08Dt.jpg][Image: 1lPUty.jpg][Image: SERDUX.jpg]
Viewing all 14108 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>