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

Spark problem

$
0
0
Hi everyone,
I'm having an issue with the CodeIgniter 4 CLI (spark). It suddenly stopped working and now it doesn't output anything, no errors, no messages, not even php spark --help. It simply runs and finishes silently.

So far I’ve tried:

Downloading a fresh spark file from the framework,

Making sure it has execute permissions (chmod +x spark),

Running it with different PHP versions (php -v confirmed working),

Checking writable/logs, no logs are generated when running it.

Nothing has changed in my project configuration to my knowledge, and it used to work earlier.

Has anyone experienced something similar or could point me toward potential causes?

Screenshot: https://i.imgur.com/fn0PbXN.png
Thanks in advance!

Updating codeigniter show error problem

$
0
0
HI , i update codeigniter at version 4.6 , when i have an error in debug mode the system show :

Fatal error: Uncaught Error: Call to undefined method CodeIgniter\Debug\ExceptionHandler::cleanPath()

Which file must i  modify ?

Question about modules

$
0
0
Good morning, I am following the instructions at the link https://codeigniter4.github.io/userguide...dules.html to add modules to my project.
The project structure is something like this:

Code:
myproject/
├── app/
│  ├── Controllers/
│  │  └── Home.php
│  └── Config/
│      └── Autoload.php
├── OrganizationName/
│  ├── Module01/
│  │  ├── Commands/
│  │  │  └── Command01a.php
│  │  ├── Controllers/
│  │  │  └── Controller01a.php
│  │  └── Views/
│  │      └── index.php
│  └── Module02/
│      ├── Controllers/
│      │  └── Controller02a.php
│      │  └── Controller02a.php
│      └── Views/
│          └── index.php


I modify app/Config/Autoload.php

PHP Code:
<?php

namespace Config;

use 
CodeIgniter\Config\AutoloadConfig;

class 
Autoload extends AutoloadConfig
{
    // ...
    public $psr4 = [
        APP_NAMESPACE => APPPATH,
        'OrganizationName'  => ROOTPATH 'OrganizationName'// <-- Add this
    ];

    // ...



Everything was working fine until now, but when I tried to run the command within module01, it failed (it did not appear when running php spark list).
My command is like:

PHP Code:
<?php

namespace OrganizationName\Module01\Commands;

use 
CodeIgniter\CLI\BaseCommand;
use 
CodeIgniter\CLI\CLI;

class 
TestCommand extends BaseCommand
{
    protected $group 'custom';
    protected $name 'test:run';
    protected $description 'Testing from external module';

    public function run(array $params)
    {
        CLI::write('Command Works!');
    }


The first thing I tried was to configure app/Config/Modules.php and add

PHP Code:
public $enabled true;
...
public 
$aliases = [
    'events'    => true,
    'filters'    => true,
    'registrars' => true,
    'commands'  => true// <-- Add this
]; 


and it didn't work.
Perhaps I misunderstood and should add the modules one by one in app/Config/Autoload.php
I tried modifying app/Config/Autoload.php

PHP Code:
<?php

namespace Config;

use 
CodeIgniter\Config\AutoloadConfig;

class 
Autoload extends AutoloadConfig
{
    // ...
    public $psr4 = [
        APP_NAMESPACE => APPPATH,
        'OrganizationName' => ROOTPATH 'OrganizationName',
        'OrganizationName\Module01' => ROOTPATH 'OrganizationName/Module01'// <-- Add this
    ];

    // ...



And now I was able to execute the command.
So my question is, should I add all my modules one by one, or can I add the main path to my modules and then those modules for which I have commands?
Thank you very much in advance.
Best regards.

Sebastián

Cách gọi API + cache kết quả hiệu quả trong CI4 cho project nhỏ

$
0
0
Chào anh em CI4!

Mình đang viết một module nhỏ trong CodeIgniter 4.5.5 để quản lý lịch sửa chữa thiết bị (tai nghe, loa…). Mình cần gọi một API đơn giản để lấy danh sách lỗi thường gặp + giá tham khảo.

Hiện tại mình đang dùng curlrequest như sau:

```php
public function getCommonErrors()
{
    // API mẫu trả về JSON danh sách lỗi thường gặp của AirPods
    $apiUrl = 'https://sua-chua-airpods.weebly.com/api/errors.json';
   
    $client = \Config\Services::curlrequest([
        'timeout'        => 10,
        'connect_timeout' => 5,
        'http_errors'    => false
    ]);

    $response = $client->get($apiUrl);

    if ($response->getStatusCode() === 200) {
        $data = json_decode($response->getBody(), true);
        return $this->response->setJSON($data);
    }

    return $this->response->setJSON(['errors' => []]);
}
Câu hỏi của mình:

Anh em thường dùng library nào nhẹ hơn curlrequest cho các API đơn giản như thế này? (Guzzle quá nặng cho project nhỏ)
Cách cache kết quả API trong 10–15 phút hiệu quả nhất hiện nay là gì? Mình thử Cache Redis nhưng config hơi rườm rà.
Nếu muốn retry tự động khi API timeout thì nên wrap thế nào cho gọn?

Cảm ơn anh em nhiều! Nếu có code mẫu hay thì cho mình xin với ạ.

Codeigniter 4 Admin Starter/Boilerplate Resources

$
0
0
Modern, production-ready CodeIgniter 4.6.3 boilerplate designed for building secure, scalable, modular web applications using PHP 8.3, MySQL, CodeIgniter Shield, and CodeIgniter Settings.
It includes a fully integrated authentication system, role-based sidebar menus, Bootstrap-based responsive layouts, DataTables, SweetAlert2 notifications, a dynamic scaffolding engine for auto-generating CRUD modules, and a clean development experience with reusable helpers, traits, a consistent UI pattern, and optional modular architecture.

This starter is built for real-world enterprise apps—fast to scaffold, easy to maintain, and structured to adapt for long-term development across multiple projects.

Not that it is needed, but I was going to post this on CodeCanyon but releasing here for everyone, Let me know if you have any questions, issues or other feedback.

https://github.com/delzey/CI4-Admin-Star...oilerplate


[Image: Sales_Image.png?raw=true]
[Image: Menu_Manager.png?raw=true]

DatetimeCast, Milliseconds and PostgreSQL

$
0
0
I am just getting stared with CodeIgniter. I have written a simple Model and want to use DatetimeCast so I can interact with a TIMESTAMP WITH TIMEZONE as a proper DateTimeobject.
My Model looks as follows:
PHP Code:
class IgConfigModel extends Model
{
    protected $table 'ig_config';
    protected $useAutoIncrement false;
    protected $allowedFields = [
        'id',
        'access_token',
        'access_token_expires',
    ];
    protected $returnType IgConfig::class;

    protected array $casts = [
        'access_token_expires' => 'datetime',
    ];

To make CodeIgniter use sub-seconds, I have changed the dateFormat configuration in Database:
Code:
'datetime' => 'Y-m-d H:i:s.uP'
When inserting, everything works fine. However when loading data from the database, PostgreSQL will not include any sub-second values if they are 0. For example it will return 2025-12-08 21:20:00.123456+00:00 but for 2025-12-08 21:20:00.000000+00:00 it will return 2025-12-08 21:20:00+00:00. So then DatetimeCast fails to parse the string as the given format. 
How can I achieve this?
Thank you for any guidance.

feat(route): Add optional Route Placeholders

$
0
0
Currently, the route placeholders (:num, :hash), etc. are required. I would like to see some optional route placeholders, like, (:?num) or (:num?), whichever syntax is better.
This will help combining two functions, getBlogs() and getBlog(int $id) into one, getBlogs(?int $id) (or something similar).
I was looking at the internal working of the Routing and found that its not that hard to implement this.
But just one thing is bothering me. If a route has multiple placeholders and any of them is optional except the last one, how to determine which placeholder to give which value.
Let me give you one example.
Suppose route is defined as:

PHP Code:
$routes->get('blogs/(:alphanum?)/(:alpha)''Blogs::getBlogs/$1/$2'); 

Then, the route will give misleading results, for e.g.,
  • blogs/blog123/US will translate to Blogs::getBlogs('blog123', 'US'); This is correct.
  • blogs/US might work, as I haven't fully checked the regex handling of the routes, so, can't comment on this.
  • blogs/blog123 will give 404. This is okay.
Maybe, we can do like, only allow optional route at the last spot?
Or, maybe figure out something else?

Note: I will be using optional route placeholder ONLY at the last position. I am just shedding light on some other edge cases that might cause harm to the system.

Motivation: Laravel Routing Optional Parameters

CodeIgniter v4.6.4 Released

$
0
0
We’re pleased to announce the release of CodeIgniter v4.6.4, a maintenance update focused on improving framework stability, developer experience, and internal consistency. This release brings a wide range of bug fixes across the database layer, validation, debugging tools, and core utilities, along with several thoughtful refactors that enhance code quality and type safety.

?️ Bug Fixes

This version includes numerous fixes that strengthen reliability across the framework:
  • Improved database behavior, including corrected handling of shared/non-shared connections, more accurate field data defaults for SQLSRV and OCI8, and refined behavior for PostgreSQL column modifications.
  • Better consistency in model operations, correcting created_at handling in Model::replace() and ensuring proper casting in batch insert and update operations.
  • Enhanced stability in query compilation, SQLite3 password handling, and the valid_base64 rule.
  • Debug toolbar improvements addressing edge cases in logs collection, view hints toggling, and controlled cell behavior.
  • More robust exception responses involving resources and closures, and correct quoting of reserved keywords (including timestamp) in session tables.
  • Additional refinements such as safer Redis cache deletion, proper IDs for toolbar form fields, and disabled echo output in the preload file.
? Refactoring & Code Improvements

This release also includes several internal refinements aimed at improving type accuracy, documentation, and overall maintainability:
  • Updated type hints in ResponseTrait, improved phpdocs, and removal of redundant property declarations in BaseController.
  • Cleaner and more predictable behavior in utilities such as CheckPhpIni, Language, and UserAgent.
  • Ongoing improvements for static analysis compatibility, including phpstan-related cleanup and enhanced typing across the codebase.

This update is recommended for all users. As always, thank you to our contributors for their continued effort in keeping CodeIgniter fast, robust, and developer-friendly.

Happy coding! ✨

feat(encryption): Add previous keys fallback option

$
0
0
I am creating a website that has admin panel that allows admins to rotate encryption keys hassle free. But the problem is, the encrypted data stored in database is too large (in 100s of GBs) so, its not feasible to decrypt all data and encrypt it with new keys instantly, which might lead of huge data loss.
Laravel has that feature that I want, Rotation of Encryption Keys, but, migrating to Laravel is not feasible at this stage, so, I want to ask the CodeIgniter 4 maintainer community if they could create similar feature in CodeIgniter 4 feature.
I am ready to create an initial PR for this feature. It will not be a breaking change (AFAIK), there can be a boolean variable something like $previousKeysFallbackEnabled, which can be set to true if anyone wants to use this feature, for others, it would be false by default.

By using this feature, in my website, I would temporary set the current encryption key to previous, and start a background task to decrypt all old data with new encryption key, while the encrypt function will only encrypt with newer key, so, new data is already proper. And when that task is completed, remove the old key from the previous keys. And everyone's happy.

Thank you CodeIgniter 4 Team!!

Git’s New Era: What Git 2.52 and the Road to Git 3.0 Mean for Developers in 2026

$_REQUEST not containing $_GET

$
0
0
Hi,
I'm experiencing an issue where the $_REQUEST doesn't contain $_GET. Here what those 2 arrays look like:
$GET: ["course-activity-form" => "325"]
$_REQUEST: ["/activities/register" => "" ]
The content of $_REQUESTand $_GET starts the same. But the, as the SiteURIFactory's parseRequestURI executes, the $_GET is modified here:
PHP Code:
        // Update our global GET for values likely to have been changed
        parse_str($this->superglobals->server('QUERY_STRING'), $get);
        $this->superglobals->setGetArray($get); 
$_GET receives the query part of the URL, $_REQUEST remains untouched.
But later, when I validate on the URL parameters, the validation code looks at the $_REQUEST, doesn't find the parameter and fails.
I'm on:
PHP: 8.3
CodeIgniter: 4.5.5

Any help in fixing this properly would be appreciated.

I created the Igniter CMS. An open-source, free CMS built with CodeIgniter 4

$
0
0
About a year ago, I began this as a side project for some client work, and it has now developed into a fully functional CMS. Since it's free and open source, I thought I'd share it with the community.
built on CodeIgniter 4 with an emphasis on modernity without being unduly complicated. contains the standard CMS features, such as media handling, roles and permissions, content management, themes, and a tidy admin interface.
Happy to answer questions or hear feedback if anyone tries it out.

Module manager

$
0
0
I would like to share a small helper package for CodeIgniter 4 that focuses on managing the lifecycle of modules.

Modules themselves are a core feature of CodeIgniter 4. This package does not introduce a new module system - it simply helps with common lifecycle tasks such as:
  • Installing and uninstalling modules
  • Registering module namespaces
  • Running module migrations during installation and update
  • Enabling and disabling modules without removing files

The goal is to reduce manual steps when working with modular CI4 applications, while staying aligned with the framework’s built-in module support.

Repo: https://github.com/michalsn/codeigniter-module-manager
Docs: https://michalsn.github.io/codeigniter-module-manager/

Merry Christmas

$
0
0
Merry Christmas Everyone
and Have a
Happy New Years.

Global Exception Handler

$
0
0
Hi,  i've read the documentation on how to create Custom Exception Handlers. But i wan't to know what is the best practice to make. I'm planning to make my custom exception handler redirect back/to previous url with it's error message(probably will use session flash message) if it's from form post or return ajax error response if it's from ajax/api calls. But not for all exception, e.g. just some 4xx error or some from database error. I appreciate if you can guide with code example.
Thank's.

Simplifying Package View Overrides using ViewableTrait

$
0
0
Hi everyone,

I've been working heavily on modular applications recently, and I've hit a friction point that I think we can solve: Customizing Package Views.

Currently, the standard approach in many libraries (like CodeIgniter Shield) involves defining every single view path in a Config file. While explicit, this leads to Config Hell as the project grows.

The Problem:
To allow users to override views, we force them to manage a massive array of paths.

Before (Explicit Config):

PHP Code:
// Config/Auth.php
public $views = [
    
'login' => 'Shield\Views\login',
    
'register' => 'Shield\Views\register',
    
// ...
];

// Controller
return view(config('Auth')->views['login']); 

I propose utilizing a ViewableTrait that relies on Convention over Configuration. It automatically resolves the view based on a priority cascade.

PHP Code:
// Controller
use ViewableTrait;

return 
$this->viewByPriority('login'); 

How it works:
The trait checks for the file in the following order and renders the first one found:

App Override: App/Views/path/to/login.php (User custom view)

Module Original: Module/Views/path/to/login.php (Package view)

Why this is better:

Zero Config: Developers can override a package view simply by creating a file in their App/Views folder. No config changes required.

Cleaner Code: Removes the need for bloated config arrays holding view paths.

Better DX: It follows a predictable pattern that is easy to document and use.

I'd love to hear your thoughts. Do you see value in integrating this logic directly into the CodeIgniter Core?
Instead of every package reinventing the wheel, having a native ViewableTrait would standardize how modules handle view overrides and save us all from writing repetitive config boilerplate.

DEV: Using CodeIgniter in 2025: Pros and Cons

Routing using a database

$
0
0
Hey all,

Using CI 4.6, php 8.4 on Apache.

My routes file is getting to be a bit unwieldy at over 1,000 lines. I checked the documentation and didn't see anything about using a database for manual routing and was wondering if anyone has done this before and is willing to share how they accomplished it. Seems like something that would be doable, but not entirely sure where to start. 
Seems like it would be a lot easier to maintain with a standard CRUD type interface rather than trying to scroll through 1,000 lines looking for the right section/route to add/edit a rule. One caveat would be that I do have my routes in groups for security (using ci-4-auth from Lewe - need to convert to Shield one of these days!). So that would have to be maintained.
Short example:

PHP Code:
/* --------------------------------------------------------------------
* LOGGED IN USERS - EXCEPT VENDORS && DISPATCHERS
* --------------------------------------------------------------------*/
$routes->group('', ['filter' => 'role:Super Admin,Mgmt. Admin,Admin,WVM Office,Mgmt. Reps,Reps'], function ($routes) {
 
$routes->get'admin/lots/new_lot''Admin\Lots::new_lot', ['filter' => 'userHistory:Lots - Create New']);
 
$routes->get'admin/lots/new_lot/(:any)''Admin\Lots::new_lot/$1', ['filter' => 'userHistory:Lots - Create New']);
 
$routes->post'admin/lots/create_lot''Admin\Lots::create_lot', ['filter' => 'userHistory:Lots - Save New']);
 
$routes->match(['GET''POST'], 'admin/lots/edit_lot/(:any)''Admin\Lots::edit_lot/$1', ['filter' => 'userHistory:Lots - Edit Existing']);
 
$routes->post'admin/lots/update_lot/(:any)''Admin\Lots::update_lot/$1', ['filter' => 'userHistory:Lots - Save Existing']);
 
$routes->match(['GET''POST'], 'admin/lots/lot_history/(:any)''Admin\Lots::lot_history/$1', ['filter' => 'userHistory:Lots - View History']);
 
$routes->match(['GET''POST'], 'admin/lots/lot_proof/(:any)''Admin\Lots::lot_proof/$1', ['filter' => 'userHistory:Lots - Create Proof']);
 
$routes->match(['GET''POST'], 'admin/lots/duplicate/(:any)''Admin\Lots::duplicate/$1', ['filter' => 'userHistory:Lots - Duplciate']);
 
$routes->match(['GET''POST'], 'admin/lots/upload_lot_doc/(:any)''Admin\Lots::upload_lot_doc/$1', ['filter' => 'userHistory:Lots - Upload Document']); 

Any suggestions are appreciated.

Best way to add webfinger .well-known/webfinger

Codeigniter 4 SMTP with IONOS

$
0
0
Hi,
Having some issues getting the Codeigniter 4 SMTP system to send emails using IONOS.
We just get a general failure message "Unable to send email using SMTP. Your server might not be configured to send mail using this method"
Would appreciate any guidance and help on what might not be quite right.

codeigniter/app/Config/Email.php is as follows
PHP Code:
<?php

namespace Config;

use 
CodeIgniter\Config\BaseConfig;

class 
Email extends BaseConfig {

    public string $fromEmail  'noreply@domain.co.uk';
    public string $fromName  'Email Sender Name';
    public string $recipients '';

    // The "user agent"
    public string $userAgent 'CodeIgniter';

    // The mail sending protocol: mail, sendmail, smtp
    public string $protocol 'smtp';

    // The server path to Sendmail.
    public string $mailPath '/usr/sbin/sendmail';

    // SMTP Server Hostname
    public string $SMTPHost 'smtp.ionos.co.uk';

    // SMTP Username
    public string $SMTPUser 'noreply@domain.co.uk';

    // SMTP Password
    public string $SMTPPass 'password';

    // SMTP Port
    public int $SMTPPort 465;

    // SMTP Timeout (in seconds)
    public int $SMTPTimeout 10;

    // Enable persistent SMTP connections
    public bool $SMTPKeepAlive FALSE;

    /* SMTP Encryption.
    * @var string '', 'tls' or 'ssl'.
    *      'tls' will issue a STARTTLS command to the server.
    *      'ssl' means implicit SSL.
    *      Connection on port 465 should set this to ''.
    */
    public string $SMTPCrypto '';

    // Enable word-wrap
    public bool $wordWrap TRUE;

    // Character count to wrap at
    public int $wrapChars 76;

    // Type of mail, either 'text' or 'html'
    public string $mailType 'html';

    // Character set (utf-8, iso-8859-1, etc.)
    public string $charset 'utf-8';

    // Whether to validate the email address
    public bool $validate FALSE;

    // Email Priority. 1 = highest. 5 = lowest. 3 = normal
    public int $priority 3;

    // Newline character. (Use “\r\n” to comply with RFC 822)
    public string $CRLF "\r\n";

    // Newline character. (Use “\r\n” to comply with RFC 822)
    public string $newline "\r\n";

    // Enable BCC Batch Mode.
    public bool $BCCBatchMode FALSE;

    // Number of emails in each BCC batch
    public int $BCCBatchSize 200;

    // Enable notify message from server
    public bool $DSN FALSE;


Viewing all 14353 articles
Browse latest View live


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