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

Hard Delete when useSoftDeletes = true;

$
0
0
Is there anyway to physically delete a database record when usesoftdeletes == true?  Can usesoftdeletes be overidden temporarily?
Thank you!

URI routing from CLI

$
0
0
I'm encountering an issue with a route when calling it from the CLI. I think this may very well be a feature rather than a bug!
I have a cli method which expects 3 parameters all as strings. This is the route:
PHP Code:
$routes->cli('cli/postbyid/(:segment)/(:segment)/(:any)''Cli::postbyid/$1/$2/$3'); 

By and large this works, except when the third string contains characters that normally wouldn't be permitted by ar URI. For example:
Code:
php index.php cli param1 param2 param3(b)

The brackets in the third parameter cause an exception to be thrown:
Code:
CodeIgniter\HTTP\Exceptions\BadRequestException: The URI you submitted has disallowed characters: "param3(b)"

I can see that this is correct behaviour for security reasons when specifying URIs, but a CLI parameter isn't a URI.
I've tried adding a custom placeholder permitting *any* characters at all, but this still throws the same error as I suspect it is still restricted by config/App.php. Hopefully I've explained this in a way that it can be understood. I think CI is performing as designed, but is creating an unnecessary restriction for CLI access. I suspect the solution is for CLI access to ignore character restrictions on URIs, or that any custom placeholder should not be restricted by the characters specified in the config.

Edit: I'm using CI 4.6.0

Updating ci with composer problem with shield's route

$
0
0
HI , i have this error :
Call to a member function routes() on null
at APPPATH/Config/Routes_gestionale.php:19
 this is my Route.php :

Code:
<?php

use CodeIgniter\Router\RouteCollection;

/**
* @var RouteCollection $routes
*/

require 'Routes_vetrina.php';


require 'Routes_gestionale.php';

and this is my Routes_gestionale.php

Code:
<?php






############################################################################################################
############################################################################################################
#                                      GESTIONALE
############################################################################################################
############################################################################################################

/*
    * --------------------------------------------------------------------
    * AUTH
    * --------------------------------------------------------------------
    */
service('auth')->routes($routes); //line 19
How can isolve it ?

composer upgrade to 4.4.8

$
0
0
Get
Code:
composer audit
The new audit.abandoned setting (currently defaulting to "report" will default to "fail" in Composer 2.7, make sure to set it to "report" or "ignore" explicitly by then if you do not want this.
Found 1 security vulnerability advisory affecting 1 package:
+-------------------+----------------------------------------------------------------------------------+
| Package          | codeigniter4/framework                                                          |
| CVE              | CVE-2025-24013                                                                  |
| Title            | Missing validation of header name and value in codeigniter4/framework            |
| URL              | https://github.com/advisories/GHSA-x5mq-jjr3-vmx6                                |
| Affected versions | <4.5.8                                                                          |
| Reported at      | 2025-01-21T21:13:40+00:00                                                        |
+-------------------+----------------------------------------------------------------------------------+
Should I be concerned? What should I do?

passing variable - shows invalid variable ...

$
0
0
this should have been easy.... but for some reason its not working ...
Controller..
Code:
<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\UserModel;

class Login extends BaseController
{
    public function index()
    {
        return view('login');
    }
 
    public function authenticate()
    {
        $session = session();
        $userModel = new UserModel();

        $email = $this->request->getVar('email');
        $password = $this->request->getVar('password');
       
        $user = $userModel->where('user_email', $email)->first();
       
        if(is_null($user)) {
            return redirect()->back()->withInput()->with('error', 'Invalid username or password.');
        }

        $pwd_verify = password_verify($password, $user['user_pass']);

        if(!$pwd_verify) {
            return redirect()->back()->withInput()->with('error', 'Invalid username or password.');
        }

        $ses_data = [
            'user_id' => $user['user_id'],
            'user_email' => $user['user_email'],
            'isLoggedIn' => TRUE
        ];

        $session->set($ses_data);
        $data = array("js_to_load"=> "hello");
     
       
        //$data['js_to_load']=array("https://cdn.datatables.net/2.2.2/js/dataTables.js","https://cdn.datatables.net/2.2.2/js/dataTables.tailwindcss.js");

        return view( '/dashboard', $data);
 
       
       
    }
}
View - dashboard
Code:
<?=$this->extend("layouts/postlogin_layout")?>
 
<?=$this->section("content")?>

        <?php echo $js_to_load; ?>
       
 

    <?=$this->include('partials/usersettings');?>
   
<?=$this->endSection()?>
keep getting
Quote:ErrorException - Undefined variable $js_to_load
I have tried everything ..
Code:
$this->load->view('/dashboard',$data);
return view( '/dashboard', $data);
echo view('dashboard', $data);
all give the same invalid variable
if in the view i put
Code:
print_r($_SESSION);
it print's the session...
I know i am making a very small mistake some where just dont know where ...

erorr session help

$
0
0
Ölümcül hata: Uncaught ErrorException: touch (): writable / session / ci_session7b2atemvbopvjl3vim2mdfcaviebofii dosyası oluşturulamıyor çünkü C: \ xampp \ htdocs \ htdocks \ work \ system \ Session \ Handlers \ FileHandler.phFileHandler.php (193): touch ('yazılabilir / sessio ...') # 2 [dahili işlev]: CodeIgniter \ Session \ Handlers \ FileHandler- > write ('7b2atemvbopvjl3 ...', ' ' ' '__________ [yerine] [ C:\ xampp \ htdocs \ htdocks \ vendor \ codeigniter4 \ framework \ system \ Session \ Handlers \ FileHandler.php hatta 193 
Klasörler var ve hatta söylediği dosyayı oluşturuyor ama bu hatayı alıyorum

English Translation:

Code:
Fatal error : Uncaught ErrorException: touch(): cannot create file
writable/session/ci_session7b2atemvbopvjl3vim2mdfcaviebofii
because C:\xampp\htdocs\htdocks\work\system\Session\Handlers\FileHandler.phFileHandler.php(193):
touch('writable/sessio...')#2 [internal function]:
CodeIgniter\Session\Handlers\FileHandler->write('7b2atemvbopvjl3...',' ' ''__________ [instead of][ 
C:\xampp\htdocs\htdocks\vendor\codeigniter4\framework\system\Session\Handlers\FileHandler.php  even  193
The folders exist and even create the file it says but I get this error

How, what, where?

$
0
0
At the moment I have an application running in CI4 but I want to rewrite it;

For the following reasons:
- Never worked with a (PHP) Framework before so the code is quite sloppy.
- It started as a hobby project, which it still is, but now about 30 people use it and this is going to grow.
- I now work in the production environment and that is of course not really the intention.

I am just getting a bit overwhelmed with all the possibilities that are now available. My knowledge in JS is quite low and so I have looked at for example React, Vue etc., but I do not know if a SPA is necessary since I only want to add a few active elements.

Now I once asked around and one advises CodeIgniter the other Laravel with for example Vue/React (Inertia) or Alpine (AJAX)... "CodeIgniter is death" etc. etc. etc.. There is too much, lol!

Have you ever faced this choice? I will always be the only one who will manage this project. 

How, what, where?

s There a Feature Like Laravel Octane in CodeIgniter 3/4?

$
0
0
Hello, everyone!

I’ve been using CodeIgniter (both 3 and 4) for some projects, and I’m wondering if there’s any built-in or third-party feature similar to Laravel Octane that can optimize performance by keeping the application in memory.

Since PHP runs in a request-response cycle, it reloads the framework and bootstraps everything on every request, which can make it slower compared to solutions that leverage long-running processes like Octane (which uses Swoole, RoadRunner, or FrankenPHP). Laravel Octane significantly improves performance by keeping the application in memory and handling requests more efficiently.

Does CodeIgniter have anything similar to this? If not, are there any recommended ways to improve performance, like caching or using an alternative server?

Thanks in advance!

Using Entities with Models

$
0
0
I am using entities with my models, I would like the foreign keys to be saved as the ID in the model but the relevant entity in the table entity. For example: The Activity Model has the Venue ID as an integer but the Activity Entity has it stored as a Venue Entity. How do I do this?

Undefined function esc() in v4.5.8

$
0
0
with:
Code:
<title><?= esc($title ?? 'Default Title') ?></title>
get error after upgrading:
Code:
PHP Fatal error:  Uncaught Error: Call to undefined function esc() in /var/www/mvc/xa/app/Views/templates/xaHeader.php:7
Stack trace:
#0 {main}
  thrown in /var/www/mvc/xa/app/Views/templates/xaHeader.php on line 7
Any ideas why?

help w/testing: variables not passed to view in 4.5.4

$
0
0
Hi,
I'm using 4.5.4 and I'm trying to set up some tests but I'm having a difficult time. This is the code from my controller:
Code:
    $data['is_new'] = $is_new;
    return view('my_body', $data);
Then in the view I have this:
PHP Code:
<?php

?>
  if ($is_new) {
    <?php
      
print "Welcome, new user.";
    ?>
  } else {
      print "Welcome back.";
  } 


In my test, which I pretty much copied from the docs:
PHP Code:
<?php
  
namespace app\Controllers;
  use CodeIgniter\Test\CIUnitTestCase;
  use CodeIgniter\Test\FeatureTestTrait;
  use CodeIgniter\Test\DatabaseTestTrait;
  use PHPUnit\Framework\Attributes\TestDox;

  class MyControllerFeaturesTest extends CIUnitTestCase
  
{
    use FeatureTestTrait;
    use DatabaseTestTrait;
    /**
    * setup and teardown run before and after
    * the _entire_ test case
    * setup and tearDown run _between_ tests
    */
    public static function setUpBeforeClass(): void
    
{
      parent::setUpBeforeClass();
    }
    public static function tearDownAfterClass(): void
    
{
      parent::tearDownAfterClass();
    }
    protected function setUp(): void
    
{
      parent::setUp(); // Do not forget

      helper('text');
    }
    protected function tearDown(): void {
      parent::tearDown();
    }

    #[TestDox('A new user should get a welcome')]
    public function testViewingResults(): void
    
{
      $response $this->get('/forum/loggedin/79435')
                        ->call();
      $response->assertSee('Welcome, new user');
    }
  



The error I'm getting is that $is_new is not defined in the view:
Code:
ErrorException: Undefined variable $is_new

The page actually works just fine, no errors at all. I can go to the url, see the appropriate message based on whether or not I'm a new user. 

Any ideas?

DB Connection::execute() - error handling

$
0
0
PHP Code:
    protected function execute(string $sql)
    {
        while ($this->connID->more_results()) {
            $this->connID->next_result();
            if ($res $this->connID->store_result()) {
                $res->free();
            }
        }

        try {
            return $this->connID->query($this->prepQuery($sql), $this->resultMode);
        } catch (mysqli_sql_exception $e) {
            log_message('error', (string) $e);
            if ($this->DBDebug) {
                throw new DatabaseException($e->getMessage(), $e->getCode(), $e);
            }
        }
        return false;
    
My issue is: when encountering a duplicate key error (1062), the exception is caught, but NOT re-thrown UNLESS using the DBDebug flag.

Using SQL's INSERT IGNORE, the exception is not thrown. But, there is no error code from $this->db->error(). The only way I can think to detect the duplicate to use a transaction, do a SELECT, if that fails then do an INSERT.

Looking at this code, to me the if ($this->DBDebug) condition looks plain wrong. It's an accident waiting to happen. Using DBDebug and an appropriate try/catch block in the user's code, all works fine and dandy. In production, the code aborts because there is no re-throw.

It would be interesting to know the rationale for the dual behaviour. execute() must be one of the most commonly used methods in the framework.

Apologies if this has already been covered elsewhere. If I get time I'd like to update the documentation, the duplicate key handling required does not appear to be covered.

Wrong phpunit.xml.dist shipped?

$
0
0
Hi everyone,
I've checked Github and there is an updated phpunit.xml.dist from 2 month ago, but it still (or again) shows in line 5
PHP Code:
    bootstrap="system/Test/bootstrap.php" 
and this was fixed here https://github.com/codeigniter4/CodeIgniter4/pull/8785 and probably should read like
PHP Code:
bootstrap="vendor/codeigniter4/framework/system/Test/bootstrap.php" 

Florian

CI4 Shield, Users, Groups, Permissions managment

$
0
0
Hi
I want to make an admin panel like Users managment ( list/add/edit/update/delete ) and same for Groups and Permissions. As i saw from Shield docs there is no solution for this, only assign groups and permission from Shield functions.

Shield\Config\AuthGroups config class
PHP Code:
public array $groups = [
    'superadmin' => [
        'title'      => 'Super Admin',
        'description' => 'Optional description of the group.',
    ],
]; 
same as permissions 
PHP Code:
public array $permissions = [
    'admin.access'        => 'Can access the sites admin area',
    'admin.settings'      => 'Can access the main site settings',
    'users.manage-admins' => 'Can manage other admins',
    'users.create'        => 'Can create new non-admin users',
    'users.edit'          => 'Can edit existing non-admin users',
    'users.delete'        => 'Can delete existing non-admin users',
    'beta.access'        => 'Can access beta-level features'
]; 
Barrier with this kind of groups and permission i get into is that i will have system for maange Employees, Vehicles, Users, WebsiteSettings, and many other controllers. So this means i would need to add each controller.method to the file and permissions, but i want to make this dynamic so lets say Admin can create groups and permissions and save in database.

Is that means if i don't use config based permission and groups i cannot use a Shield and hes functions to check if user have permission to access controller/method ?

insertBatch Auto Split

$
0
0
Hello,
i use insertBatch with more than 20.000 data from a file. Sometimes there are same entrys with a unique key. Now i try to catch the duplicate entry error instead of an exception and errorpage, but it wont work the suggested way.
What i'll do:
Turn off DBDebug in Database.php (set to false)
and then
PHP Code:
try { 
$Model->insertBatch($data); 
}catch (
Exception $e){
echo 
$e->getMessage();

Doesnt work!

Next
PHP Code:
$Model->insertBatch($data);
if(
$Model->error()['message']>''){
                var_dump($Model->error()['message']);
            
Work with small amount of Data doesnt work with large Data!

As i see it inserts the Data till error, than some not and than the rest but doesnt give the error back.

Testscript:
PHP Code:
$data = [];
$data[] = ['name'=>'Hans','wert'=>1];
        for($i=0;$i<5000;$i++){
            $data[] = ['name'=>'Tom_1'.$i,'wert'=>1];
        }
        $data[] = ['name'=>'Hans','wert'=>1];
        for($i=0;$i<5000;$i++){
            $data[] = ['name'=>'Tom_2'.$i,'wert'=>1];
        

Name is the primary key!
After i have 9901 Entry without error.

What am i missing?

Best regards

CodeIgniter France

$
0
0
Hello everyone!
After nearly five years of using CodeIgniter, creating my own CMS that now powers 14 French companies, and recently partnering with two other French CodeIgniter 4 developers, I’ve noticed that CodeIgniter is not very popular in France due to a general lack of awareness.

To address this, I’ve taken the initiative to create CodeIgniter France, a completely free and open-source platform dedicated to promoting CodeIgniter. The site will feature updates on patches, tutorials (both blog and video), and insights into the advantages of CI 4 in 2025.

Here’s a first preview of the site! Of course, I’m open to working with the official CI team to add relevant links and further highlight CodeIgniter in France.

The goal of CI France is to bring together French-speaking developers, facilitate learning, and showcase official CI updates.
As a passionate developer who dedicates a significant part of my professional work to CI, I felt it was important to provide this resource to the francophone community and demonstrate CodeIgniter’s power and relevance worldwide.

On top of that, I’m incredibly excited about launching a YouTube channel to help both new and experienced developers learn how to use CodeIgniter 4! ?

Link : https://codeigniterfrance.com

Looking forward to your thoughts and feedback!
Best regards
Florian

Using a third party library without composer

$
0
0
I would like to use this library in a controller but without installing it with composer. How do i go about that?
https://github.com/MaestroError/php-heic-to-jpg
Where do I put the library and how do I properly namespace it?

Does this look correct?

require APPPATH . 'ThirdParty/HeicToJpg/src/HeicToJpg.php';
use Maestroerror\HeicToJpg;

RSS with CI 4.6

$
0
0
Where can I find a simple example of RSS creation with CodeIgniter 4.6 I found example but it does not work cause old version. We should remove all 10 years old answers it is useless today

DateTime field validation

$
0
0
I'm trying to validate a dateTime field but I can't get it to work, is this not possible or am I doing something wrong?
PHP Code:
'myDateTime' => 'required|valid_date["Y-m-d H:i"]'

Problem with route on CodeIgniter API

$
0
0
Hi, I'm begining using APIs with CodeIgniter.
After create a new project, the endpoint using POST doesn't works ( POST http://localhost/lab/php/client/ do de same that GET http://localhost/lab/php/client/, return http code 200 and all de clients ).
Clearly I'm doing something wrong, but I don't realize the mistake I'm making.
Someone with more experience than me (I recently started with the API theme with CodeIgniter4) could help me.
Regards.
Sebastián
Step by step
Create a lab folder inside www
Inside the lab folder:

Code:
composer create-project codeigniter4/appstarter php
I get a structure like that:

Code:
www
└── lab/
    └── php/ (project folder)
        └── public/

Edit .env:

Code:
app.baseURL = 'http://localhost/lab/php/'


In this point if I open http://localhost/lab/php/ I see the list of files, if I open http://localhost/lab/php/public/ I see the welcome page.

After adding .htaccess file to project root with:

Code:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
<FilesMatch "^\.">
    Require all denied
</FilesMatch>


Code:
www
└── lab/
    └── php/ (project folder)
        ├── .htaccess
        └── public/

When I open http://localhost/lab/php/ I see the welcome page.
Now I add two controllers for do some testing (ClientController and ProductController)

PHP Code:
$routes->get('client''ClientController::index');
$routes->get('client/(:segment)''ClientController::show/$1');
$routes->post('client''ClientController::create'); 
$routes->put('client/(:segment)''ClientController::update/$1');
$routes->patch('client/(:segment)''ClientController::update/$1');
$routes->delete('client/(:segment)''ClientController::delete/$1'); 

After this i check one by one with Postman. The only one that doesn't works was POST.
POST http://localhost/lab/php/client/ do de same that GET http://localhost/lab/php/client/, return http code 200 and all de clients

I know that i can do something like this:
$routes->resource('client', ['controller' =>'ClientController']);

but after the problem i separate the routes to check one by one
Viewing all 14343 articles
Browse latest View live


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