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

cannot read javascript though it is loaded

$
0
0
I have a view with codeigniter 4.4.8 but i cant link a javascript with   
<script src="=<?= base_url('assets/js/messages.js') ?>" type="text/javascript" >
</script>
The script does appear when i paste the absolute url in the browser though, and it appears on the network tab in developer tools, but i cant debug it by clicking on debugger view option with right mouse click. The https response is 200 ok so it is loaded, but codeigniter does not "see it". When i paste it in the view, not link it , it all works fine.

What could be the issue? I am going a bit insane hahha

How can I trace this message

$
0
0
How can I trace this message, I was trying to use a github project, but I can't get past this point, I'm starting to learn how to use the framework

"Type: ArgumentCountError

Message: Too few arguments to function CI_Loader::{closure}(), 4"

PHP 8.4 support

Customizable 404 Error Pages for Specific Routes

$
0
0
Currently, CodeIgniter allows developers to override the default 404 error page using the $routes->set404Override() method. This is useful when you want a custom 404 page across the entire application. However, in some cases, especially in larger applications or when using packages, there is a need to define custom 404 error pages for specific routes or route groups. Unfortunately, at the moment, CodeIgniter doesn't offer native support for handling route-specific 404 errors.

But in many web service(API) projects, there is a need to define custom 404 error pages for specific routes or groups of routes.


Global Impact of $routes->set404Override():

When we use the $routes->set404Override() method in CodeIgniter, the custom 404 page applies globally across the entire project. For instance, if you are working on a package that has its own route definitions and use this method like:

PHP Code:
$routes->set404Override('Datamweb\BlankCI\Controllers\Errors::Show404'); 

This override affects the entire project, not just the specific routes related to your package. As a result, all other parts of the application that depend on their own 404 error behavior will be overridden by this configuration. This makes it impossible to isolate different behaviors for different routes or contexts, leading to conflicts between different components of the project.

Multi-Module or Package Applications:

In projects with multiple modules or packages, different components may require distinct 404 behaviors. For example, a REST API section might need a minimal JSON response, while the frontend might require a more user-friendly HTML page for the 404 error. The current implementation makes it difficult to implement different 404 responses for different areas of the application.

Hardcoding 404 Error Handling in Controllers:

Without the ability to define custom 404 pages per route or route group, developers often have to resort to handling errors manually inside controllers. This can be cumbersome and makes the codebase harder to maintain, as each controller has to implement its own logic to check for specific methods and return custom 404 responses.

For example, developers might end up writing code like this:

PHP Code:
$routes->match(['GET''POST''DELETE','PUT' and ...],'example-route''ExampleController::method'); 

PHP Code:
  
public function method(): ResponseInterface
  
{
      if (!$this->request->is('post')) {
          return $this->formatResponse(
              'error',
              ResponseInterface::HTTP_METHOD_NOT_ALLOWED,
              "The HTTP method({$this->request->getMethod()}) used is not allowed for this endpoint.",
              null,
              ['method' => 'The HTTP method used is not allowed for this endpoint. Allowed methods are: \"POST\"."],
              null
          );
      }
  } 

While this works, it increases complexity and clutter in controllers, which should ideally focus on core business logic, not error handling.

Proposed Solution:

To address the limitations of the current implementation, I propose adding a method to the `RouteCollection` class that allows developers to set custom 404 error pages per route or route group. Here's how it could work:

New Method withCustom404() for Routes:
Developers should be able to define custom 404 pages for specific routes directly within the route definition. For example:

PHP Code:
  $routes->post'example-route''ExampleController::method')
          ->withCustom404(function() {
              return view('errors/custom404');
          }); 


In this case, if a user accesses the example-route with an unsupported method or path, the custom 404 page defined in withCustom404 will be returned instead of the global one.

Support for Grouped Routes:
The method should also support route groups, so developers can apply a custom 404 error page to a set of routes within the same group. For example:

PHP Code:
  $routes->group('api', ['namespace' => 'App\Controllers\Api'], function($routes) {
      $routes->get('users''UserController::index');
      $routes->post('users/create''UserController::create');
     
  
})->withCustom404(function() {
          return $this->respond(['error' => 'API not found'], 404);
      });; 


In this case, all routes under the `/api` namespace will return a JSON 404 error, while the rest of the application will continue using the default 404 page.

No Global Impact:

The custom 404 page defined using withCustom404() or similar should only affect the specific route or group of routes. It should not override the global 404 handler for the entire project unless explicitly set at a global level.

Adding the ability to define route-specific 404 error pages would provide a more flexible and modular approach to error handling in CodeIgniter. This feature would be especially beneficial in larger applications or in cases where developers use multiple packages, allowing for distinct behaviors without affecting the global application.

CodeIgniter for Data Analytics Reporting

$
0
0
Hello friends,
We are a core PHP developer using Bootstrap/JQuery/AJAX etc but never used any development framework. We have built a number of applications so have a good experience in core PHP. We do write elegant code that contains usable modules. However, we know we need to move forward and adapt a more modern framework which can make our apps more scalable and take less time to develop.
We are evaluating frameworks to start with. But we also have a clear requirement. The application will deal with large volumes of data and will need to display various dashboards and reports. We are considering Kool Reports for this but unsure whether Code Ignitor is the right platform for this. Thei application will be a front end for our customers to view various analytics reports.
Any guidance or help shall be appreciated.
Thank you,
Sharad

Email management with CodeIgniter

$
0
0
Hi everyone,

In the middle of developing an app with CodeIgniter, I'm working on email management. I've seen that it's easy to send emails with the native library, but I'm wondering if any of you have already integrated more advanced solutions, like managing mass mailings or newsletters. Do you use external services for this, or are you content with what CodeIgniter offers? In terms of performance and simplicity, is it worth using a dedicated service, or can you stick to the native solution without too much trouble?

Reload .env file in runtime

$
0
0
hi..
is it possible to reload the .env in runtime?
or is there a function I can use to reload the .env?

i have create new command in spark to installation my project,
with extend class BaseCommand.

i create function to generate  .env file with the value from input CLI .
before generate i validation that, include checking connection DB,table exist..etc  n i use value from CLI.

when the input valid  then i generate the .env file with that value.


the problem is  when i generate the .env in runtime, 
its cant change the first load value,  before i generate that.

a new .env can be read after the second load.
i must stop the CLI n run command again..

i want to automaticly read the env in global after i generate that.
so i can run the others command, like migration,seed automaticly after i generate the env...

can i do that?

thanks before..

CI Session files

$
0
0
Currently, within the Session library when using file - we see CI_Session_files_driver::read taking up to 120s to process  
Sessions old files are deleted but after some time I see still see these performance issues on requests tracked in NewRelic where it takes 100-120s 

Upgraded to 4.4.4, error in Session.php

$
0
0
Hi, I just upgraded CI to v 4.4.4 and now i get this error:

Code:
CRITICAL - 2024-08-24 09:26:09 --> ErrorException: Undefined global variable $_SESSION
in SYSTEMPATH/Session/Session.php on line 499.
1 SYSTEMPATH/Session/Session.php(499): CodeIgniter\Debug\Exceptions->errorHandler(2, 'Undefined global variable $_SESSION', '/home/***/system/Session/Session.php', 499)
2 APPPATH/Controllers/BaseController.php(69): CodeIgniter\Session\Session->get('character_id')
3 SYSTEMPATH/CodeIgniter.php(914): App\Controllers\BaseController->initController(Object(CodeIgniter\HTTP\CLIRequest), Object(CodeIgniter\HTTP\Response), Object(CodeIgniter\Log\Logger))
4 SYSTEMPATH/CodeIgniter.php(493): CodeIgniter\CodeIgniter->createController()
5 SYSTEMPATH/CodeIgniter.php(361): CodeIgniter\CodeIgniter->handleRequest(null, Object(Config\Cache), false)
6 FCPATH/index.php(79): CodeIgniter\CodeIgniter->run()

any help please?

Docker for local web development

$
0
0
Hi Folks!
When I searched for the PHP Framework Laravel, I came across the official documentation saying to use Laravel Sail for development.
After many hours of investigating over the internet, I found the most interesting and detailed tutorial series about Docker for local web development.
So I used it for my Codeigniter project.
Because I found it so awesome, I just wanted to share it with you.

osteel's blog - Docker for local web development

Query Binding with question mark does not work

$
0
0
I have been using the question mark all the time to mark the location of the bound values in my queries until I have met one short line of code where the question mark has refused work. I don't know why.
There notes at query bindings state that

Quote:Instead of using the question mark to mark the location of the bound values, you can name the bindings, allowing the keys of the values passed in to match placeholders in the query

I replaced the question mark with a named binding and the code worked! Why the question mark does not work, I cannot tell at all. I have tons and tons of code that use the question mark.

Test DB migration for Version 4.5 and later

$
0
0
Thank you for your help.

For a long time, we have been managing the test DB with CodeIgniter's migration function, just like the production DB and development DB.
This was done by specifying CI_ENVIRONMENT='testing' in the .env file and running the php spark migrate command to migrate the test DB.

However, since version 4.5, this method is no longer available.
https://forum.codeigniter.com/showthread.php?tid=91098

Therefore, we added an environment setting (Config/Boot/test-migrate.php) 'test-migrate' to migrate the test DB, and added a branch to the constructor of Config/Database.php that references the test DB even during 'test-migrate' (this system references multiple DBs).


Code:
public function __construct()
{
    parent::__construct();

    // OLD: if (ENVIRONMENT === 'testing') {
    if (ENVIRONMENT === 'testing' || ENVIRONMENT === 'test-migrate') {
        $this->defaultGroup = 'tests';
    }
}


By doing this, I was able to confirm that the environment setting 'test-migrate' works as expected up to the stage of php spark migrateConfusedtatus. However, when I run php spark migrate, the migration is not performed.

Has anything changed in the 4.5 transition regarding the way the database is referenced when running php spark migrate?

(Uses machine translation JP to EN)

Filter - Return response error

$
0
0
Hi,
I have created a filter to trigger a process After a controller.
My controller (below) is very simple. Essentially, the controller receives data from an external source (webhook), assigns a variable to the data, and returns an HTTP 200 (Success) to the external server.

PHP Code:
namespace App\Controllers;

use 
CodeIgniter\Controller;
use 
App\Controllers\BaseController;

class 
Filter_Test extends BaseController {
    public function index() {
       if ($this->request->getJSON()) { 
          $external_data$this->request->getJSON();
          log_message('notice''[SUCCESS] {file}-{line}, JSON ARRAY from EXTERNAL  - '.print_r($external_data,true)); 
       }
       return $this->response->setStatusCode(200);
    }



After the above controller, the filter is executing perfectly, and running my process (below). 
My process (below) obviously fails as $bar does not exist,
PHP Code:
use CodeIgniter\Model;
use 
CodeIgniter\Database\Query;

class 
Updater {
    public function write_data($vals) {
        $foo=$bar;
    }


In this instance, Codeigniter is returning an HTTP 500 response to the external server, instead of the HTTP 200 as defined in the controller.

I do not understand how this is possible as I should have already returned HTTP 200 from the controller, and my process (Updater) should only be called AFTER the controller has finished, is this correct?

If this is not correct, is there a way to respond with HTTP 200 from the controller (this would be correct as I have received the data), and then process the data, handling any subsequent errors (data or framework) in alternative ways?

Many Thanks,

CI4 Sheild, cookie expiration change not working

$
0
0
I'm using CI4 with Shield. I want the session to stay active indefinitely. In Config\Session.php I set the "expiration" and "timeToUpdate" properties to 60 * 60 * 24 * 365 (I also tried setting to 0). However, the cookie "ci_session" that gets created has an expiration of the same day still. How do I actually change that?

Action: Set Config\Session->expiration = 60 * 60 * 24 * 365

Expectation: I expected the ci_session cookie to be created with an expiration date of next year.

Result: ci_session cookie is created with same day expiration still.

Read Only User?

$
0
0
Hey everyone,
I have a small website running with Codeigniter 4 and Shield installed, users have a login system. So one of them shouldn't be able to actually write/change data in the database.
My idea was to make a beforeupdate, beforeinsert and beforedelete callback to check for the user id, so this function looks like this
PHP Code:
protected function checkWritePermission(array $data)
    {
        $session = \Config\Services::session();

        $id auth()->id();

        if ($id === 173) return [];
        return $data;
    
but... as you experts probably see on the first glance, it doesn't work, like for updates:
CodeIgniter\Database\Exceptions\DatabaseException

You must use the "set" method to update an entry.

Is there any different way to achieve this?

Update multiple rows with where condition

$
0
0
Hi,
I want to update all rows in the database which meet a certain condition.
PHP Code:
$this->vatRatesModel->update(['default'0], ['site_id'$this->site->id]); 

But this doesn't work. When I open the debugbar, there is not even an UPDATE query.
I want to set 'default' to 0, many of them now are 1.
The 'default' field has been added to $allowedFields in the model. This works, because when I insert a record, the 'default' field is inserted as well.

How to use method function modal data to view codeigniter 4.5.3

$
0
0
i have two table cate and subcate
Modal.php below
PHP Code:
public function getCate(){}

public function 
subCate(){} 

Controller
PHP Code:
public function getCate(){

$data['getCate'] = $mCate->cate();



<strong>view</strong>
PHP Code:
how to get function subCate in view below:

foreach(
$getCate as $k =>$v){
echo 
$v;

//i want use method subcate here below
subcate $this->subcate($v->id)


can you show me how to use function method data in view above
thank

update with composer ci doen't work on development mode

$
0
0
As title , i upgrade my project on local (with laragon) and in development mode i see the preload spinner go continuosly, i think the problem is on  toolbar,.
What can i do to solve?

Database Session to restrict user login

$
0
0
I would like to restrict the user to login to only one system at a time. I am storing the session in Database, but there is no reference to the user in ci_session table. how can I insert a field to ci_session table maybe user_id and need to refer to this while user logs in from another system to delete all other sessions for that particular user. 
I am using Shield for Authentication

Create multiple email config

$
0
0
I have several email accounts from different vendors like gmail, outlook and others, is there a good way to create multiple email config so I can select one of them just like a database config?
Viewing all 14343 articles
Browse latest View live


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