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

Call to protected method CodeIgniter\Language\Language::load() from scope CodeIgniter

$
0
0
Hi,

to load translation-files and create some dynamic content, i add the language service to the _construct of my own library.

Code:
"function __construct(){ ... $this->lang = service('language');" ... }"

Now i want to load a language file by calling my lib inside a view-file in this way
Code:
"$ci->mytools->lang->load(filepath', $ci->mytools->request->getLocale(),true)"

The result is the error message: "Call to protected method CodeIgniter\Language\Language::load() from scope CodeIgniter\View\View"

What i do wrong - how i cann load a language file on each point i want?

CPanel shared hosting with multiple domains

$
0
0
I read the information on using CI4 with CPanel but I have a bit of an issue. I have several domains within my one CPanel, so my structure works as below
  • /php
  • /public_ftp
  • /public_html
  • /main-domain
  • /ssl
but, then I have the following within the /public_html/ directory:
  • /public_html/domain1
  • /public_html/domain2
  • /public_html/domain3
The very first domain I ever setup, has all the stuff for it within the /public_html/ folder, but it does have the folder outside the /public_html/ that is empty. This is not the domain I am looking to deploy to unfortunately. Is it possible to deploy to one of the domain directories inside the /public_html/ directory, because the only alternative I would have if this is not possible would be to get a second account and move that domain to that second account by itself, but that would incur additional hosting cost monthly, and I'm hoping to deploy multiple CI4 sites, but I can't afford to pay monthly hosting fees for each site I'm hoping to deploy. Any suggestions welcome because I have 14 or 15 websites I'd like to use CI4 to develop.

PHP outside the MVC structure to query database

$
0
0
Hi all,

In codeigniter v4.2, I can create /public/test.php as below instead of creating PHP in Controller, View and Routes, so that I can access it via https://example.com/public/test.php .

However in v4.5 or v4.6 it is not working. I know using MVC is the best, however somehow I really need to have many PHP outside the MVC structure that needs to query database. Appreciate if anyone can help me? Thank you all.

PHP Code:
# v4.2 supports below initialize but seems v4.5-4.6 don't

define('FCPATH'__DIR__ DIRECTORY_SEPARATOR);
chdir(FCPATH);
require 
FCPATH '../app/Config/Paths.php';
$paths = new Config\Paths();
require 
rtrim($paths->systemDirectory'\\/ ') . DIRECTORY_SEPARATOR 'bootstrap.php';
$app Config\Services::codeigniter();
$app->initialize();

$db = \Config\Database::connect();

$query $db->query("SELECT * FROM test"); 

Codeigniter VS other MVC

$
0
0
I am working on MVC for about 2 years. For me this is coolest MVC framework. I like it due to its simplicity yet vastness. I am wondered in my country, other MVC frameworks like Laravel is considered superior over CodeIgniter. Why is this so, is this consideration true or something complexity of minds?  

Thanks

Discovering Route.php and Routing.php settings in custom Modules in CodeIgniter4

$
0
0
I have different custom module paths/namespaces in my CodeIgniter4 project, and I just recently upgraded to version 4.4.0. In this upgrade the route settings will move from Config/Routes.php to Config/Routing.php file.
Now while I load my modules/namespace routes, my module routes are not identified because the $defaultNamespace setup is now in a different file.
How can I handle this?
I have added the Routes path to the $routesFiles parameter in the Routing.php 
Code:
public array $routeFiles = [
        APPPATH . 'Config/Routes.php',
        'BudgetingModule\Config/Routes.php',
        'FeeModule\Config/Routes.php',
    ];

Before upsertBatch

$
0
0
Hi everyone,
I'd like to request the addition of callbacks for upsert and upsertBatch operations in CodeIgniter4. There are currently no dedicated callbacks (similar to beforeInsert or beforeUpdate) for these actions.

Meta Info library (EAV storage)

$
0
0
I would like to announce a new library `dgvirtual/codeigniter4-meta-info`:

https://packagist.org/packages/dgvirtual...-meta-info

It is a Codeigniter4 library enabling use of Entity-Attribute-Value style storage for additional information of entities. Handy when you need to add some new data to a model but do not want (or cannot) change the database accordingly. With this library additional fields can be stored as metadata, and manipulated an retrieved on demand. 

Library is based on Users Meta Info functionality in Bonfire2

Hope you find it useful.

CI4 and sub-domain (xxx.domain.tld)

$
0
0
Hello, everyone,
I have proceeded to install CI4 via Composer on a sub-domain as in the subject.

When the procedure is completed, I get a 403 instead of the Welcome Page.

If I set a .htaccess file in the root with the following parameter:

Code:
DirectoryIndex /public/index.php


it loads the Welcome Page but everything else returns a 500 error.

Any suggestions?

When Queue Fails

$
0
0
Hi,
Please note my application is hosted on a shared hosting platform.

I am using the Queue package to process 3rd Party Webhooks, and for the most part, the Queue package is working like a dream.

However, if a queued job fails, the Queue class writes the queue data to the queue_jobs_failed table, then seems to just exit.

This is causing problems on the shared hosting platform. As per the documentation I have a CRON job executing the following every 1 minute:
Code:
php spark queue:work myqueuename

Because a failed job will just exit after writing to queue_jobs_failed table and not return the cron, the CRON does not know the job has finished executing and leaves the cron task open on the server. If the issue persists, the servers task queue quickly becomes overloaded as it starts a new cron every minute, then will eventually "crash".

I have implemented an exception handlers, where I can, to return the cron, but was wondering if there are recommendations on how to exit the Queue class (return the cron) if/when the queue fails?

When running the queue I'm considering using the suffix
Code:
--stop-when-empty

But, would the Queue class recognise the queue an empty and return the cron even after the case of a failed queue?

Note: 
I'm not sure about other environments, but if your application is hosted on a shared server and you are implementing Codeigniter Queue Package I would advise that for any development or testing you use the servers cPanel - Terminal (or similar)  to run the queue, rather than cron. That way the servers task queue does not become overloaded if the queue fails.

CodeIgniter 4.6.0 Deploy Issue

$
0
0
I deployed CodeIgniter 4.6.0, but I'm encountering a syntax error in the Config/App.php file related to the public string $baseURL declaration. When I remove the string type declaration, the error shifts to the next line. Additionally, other configuration files, such as Routes.php, are also showing similar string or array syntax errors. Can someone help me properly install and configure CodeIgniter 4.6.0?

PHP 8.4.4 Released!

$
0
0
PHP 8.4.4. This is a bug fix release.

Problems with autorouting

$
0
0
Hi,

since dynamic routes are not allowed in ci4, i try to setup the autorouting (improved) to get nearly the same situation like the ci3 dynamic routes ( i cannot and wont define for every controller own static routes).

So like the docu i do the following steps.

1) App/Routing
Code:
public bool $autoRoute = true;

2) App/Feauture
Code:
public bool $autoRoutesImproved = true;

3) App/Routes.php
Code:
//$routes->get('/', 'Home::index'); //Disabled because autorouting!
//$routes->get('mysubfolder/', '\App\Controllers\mysubfolder\mycontroller::index');//Disabled because autorouting!
 
also i have overwrite the 404error
//Error 404
Code:
$routes->set404Override(function(){ die("test routes set404 > STOPP >".$_SERVER['HTTP_HOST'].' '.$_SERVER['REQUEST_URI']); } );

If i understand it corretly, autorouting only works if there is no single static rule for the controller defined in Routes.php.

(I use the shield-authentification, maybe its important to notice, or not.)

After i do the changes, no page is avivable anymore. I only get my 404-error "test routes set404..."

Before i change it all pages will shows as they should. Now nothing works...

What i do wrong?

Db query return true if there aren't row

$
0
0
hi , i have this query : 

Code:
                $sql ='


                WITH tratta_di_riferimento as(
                    SELECT
                      mezzi_tratte.id_tratte_libere
                    FROM
                      tratte_libere as tratte
                      JOIN tratte_libere_mezzi as mezzi_tratte ON tratte.id = mezzi_tratte.id_tratte_libere
                      JOIN mezzi ON mezzi_tratte.id_mezzi = mezzi.id
                    WHERE
                      TRUNCATE (
                        6363 * sqrt(
                          POW(
                            RADIANS("'.$latitudine_partenza.'") - RADIANS(tratte.latitudine_partenza),
                            2
                          ) + POW(
                            RADIANS("'.$longitudine_partenza.'") - RADIANS(tratte.longitudine_partenza),
                            2
                          )
                        ),
                        3
                      ) < (tratte.raggio_ricerca_km + "'.$opzioni->distanza_max_tratta.'")
                      AND TRUNCATE (
                        6363 * sqrt(
                          POW(
                            RADIANS("'.$latitudine_arrivo.'") - RADIANS(tratte.latitudine_arrivo),
                            2
                          ) + POW(
                            RADIANS("'.$longitudine_arrivo.'") - RADIANS(tratte.longitudine_arrivo),
                            2
                          )
                        ),
                        3
                      ) < (tratte.raggio_ricerca_km + "'.$opzioni->distanza_max_tratta.'")
                      AND mezzi.passeggeri >= "'.$passeggeri.'"
                      AND mezzi.bagagli >= "'.$bagagli.'"
                      AND mezzi.deleted_at IS NULL
                      AND mezzi_tratte.deleted_at IS NULL
                      AND tratte.deleted_at IS NULL
                    ORDER BY
                      mezzi_tratte.costo
                                LIMIT 1
                                ),/*end tratta di riferimento [PRENDE L\'ID DELLA TRATTA CON COSTO +BASSO]*/
                  result_row as(
                    SELECT
                      mezzi_tratte.id,
                      mezzi_tratte.id_tratte_libere,
                      mezzi_tratte.id_mezzi,
                      mezzi_tratte.costo as costo_tratta,
                      mezzi.id as id_tabella_mezzi,
                      mezzi.immagine,
                      mezzi.nome,
                      mezzi.descrizione as mezzi_descrizione,
                      mezzi.passeggeri,
                      mezzi.bagagli,                 
                      mezzi.costo_km_extra,
                      tratte.latitudine_partenza,
                      tratte.longitudine_partenza,
                      tratte.latitudine_arrivo,
                      tratte.longitudine_arrivo,
                      tratte.raggio_ricerca_km
                    FROM
                      tratte_libere as tratte
                        JOIN tratta_di_riferimento on tratte.id = tratta_di_riferimento.id_tratte_libere
                      JOIN tratte_libere_mezzi as mezzi_tratte ON tratte.id = mezzi_tratte.id_tratte_libere
                      JOIN mezzi ON mezzi_tratte.id_mezzi = mezzi.id
                    WHERE
                      TRUNCATE (
                        6363 * sqrt(
                          POW(
                            RADIANS("'.$latitudine_partenza.'") - RADIANS(tratte.latitudine_partenza),
                            2
                          ) + POW(
                            RADIANS("'.$longitudine_partenza.'") - RADIANS(tratte.longitudine_partenza),
                            2
                          )
                        ),
                        3
                      ) < (tratte.raggio_ricerca_km + "'.$opzioni->distanza_max_tratta.'")
                      AND TRUNCATE (
                        6363 * sqrt(
                          POW(
                            RADIANS("'.$latitudine_arrivo.'") - RADIANS(tratte.latitudine_arrivo),
                            2
                          ) + POW(
                            RADIANS("'.$longitudine_arrivo.'") - RADIANS(tratte.longitudine_arrivo),
                            2
                          )
                        ),
                        3
                      ) < (tratte.raggio_ricerca_km + "'.$opzioni->distanza_max_tratta.'")
                      AND mezzi.passeggeri >= "'.$passeggeri.'"
                      AND mezzi.bagagli >= "'.$bagagli.'"
                      AND mezzi.deleted_at IS NULL
                      AND mezzi_tratte.deleted_at IS NULL
                      AND tratte.deleted_at IS NULL
                    ORDER BY
                      mezzi_tratte.costo),/*END RESULT ROW*/
                        result_row2 as(
                        select result_row.*,
                        TRUNCATE (
                                            6363 * sqrt(
                                              POW(
                                                RADIANS("'.$latitudine_partenza.'") - RADIANS(latitudine_partenza),
                                                2
                                              ) + POW(
                                                RADIANS("'.$longitudine_partenza.'") - RADIANS(longitudine_partenza),
                                                2
                                              )
                                            ),
                                            3
                                          ) +
                                      TRUNCATE (
                                            6363 * sqrt(
                                              POW(
                                                RADIANS("'.$latitudine_arrivo.'") - RADIANS(latitudine_arrivo),
                                                2
                                              ) + POW(
                                                RADIANS("'.$longitudine_arrivo.'") - RADIANS(longitudine_arrivo),
                                                2
                                              )
                                            ),
                                            3
                                          )-raggio_ricerca_km as km_differenza_totale
                                         
                        from result_row)/*end result_row2*/
             
                    SELECT  *,km_differenza_totale*costo_km_extra +costo_tratta as costo from result_row2;
                    ';

                    log_message('debug',$sql);

                    $res=$db->query( $sql )->getResult();

if i insert $sql in phpmyadmin return 0 row, why it return  this error:

Call to a member function getResult() on true

E-mail encoding and mixed html/text content

$
0
0

  1. Is there a way to force the text/plain part to be UTF-8, format=flowed, and content-transfer-encoding set to base64?
  2. Is there a way to force the text/html part to be UTF-8, quoted printable?
  3. Are there any more "control macros" other than {unwrap} for e-mail?

Proposal: Add isPast() and isFuture() to CodeIgniter 4 Time Class

$
0
0
Hello CodeIgniter Community! ?

I propose adding two new methods, isPast() and isFuture(), to the Time class. These methods would improve code readability, reduce complexity, and enhance efficiency when working with dates and times.


Instead of:

PHP Code:
if ($time->isBefore(Time::now())) { /* Time is in the past */ 

We can write:

PHP Code:
if ($time->isPast()) { /* Time is in the past */ 

And instead of:

PHP Code:
if ($time->isAfter(Time::now())) { /* Time is in the future */ 

We can write:

PHP Code:
if ($time->isFuture()) { /* Time is in the future */ 


Practical Use Cases:

Checking if a discount code has expired:

PHP Code:
if ($expiryDate->isPast()) {
    echo 
"The discount code has expired.";


Determining if an event is upcoming:

PHP Code:
if ($eventDate->isFuture()) {
    echo 
"This event hasn't occurred yet.";


Checking if a message should be sent:

PHP Code:
if ($sendTime->isFuture()) {
    echo 
"The message hasn't been sent yet.";


Verifying user subscription status:

PHP Code:
if ($subscriptionEnd->isPast()) {
    echo 
"Your subscription has expired.";


What Do You Think?

Task runs just once

$
0
0
Hi,
I'm not sure if I've understood the the Tasks package correctly, but, to test, I I've configured a very simple task to run every 5 minutes.
tasks.php
Code:
public function init(Scheduler $schedule)
    { 
      $schedule->call(function() {
          add_to_log_test::log_a_message();
      })->everyMinute(5)->named('testing');
    }
add_to_log_test
Code:
class add_to_log_test
{
    public static function log_a_message()
    {
         log_message('notice', '[SUCCESS] {file}-{line}, WE ARE LOGGING A MESSAGE EVERY 5 MINUTES TO TEST THE TASK SCHEDULER');
         return;
    }
}
Using terminal on my server, I run
Code:
php spark tasks:run --task testing

The task runs OK, but then stops. It does not execute the task every 5 minutes ( ->everyMinute(5)) as expected.

Code:
[server-folder]$ php spark tasks:run --task testing
Running Tasks...
[2025-02-20 10:02:58] Processing: testing
[2025-02-20 10:02:58] Executed: testing
Completed Running Tasks

[server-folder]$ 


Have I interpreted the use of Tasks incorrectly, or have I missed something ?
Any help would be appreciated.

Best Practices for Organizing Code in CodeIgniter Projects

$
0
0
I’m working on a medium-sized project using CodeIgniter, and I’m looking for advice on how to best organize my code to maintain scalability and readability. Are there any best practices you follow when structuring your controllers, models, and views?
Also, how do you manage complex business logic or large datasets in CodeIgniter to keep the performance optimal? Any tips or suggestions would be really helpful!

CI 4.6.0 and myth-auth 1.2.1 - fill placeholders problem

$
0
0
Hi
I recently updated codeigniter to version 4.6.0 and myth-auth to 1.2.1. After the update the whole app is working fine, but unfortunately adding and editing groups and permissions does not work. I get this error:
Quote:
PHP Code:
CRITICAL 2025-02-18 13:56:04 --> CodeIgniter\Exceptions\LogicExceptionThe placeholder field cannot use placeholdername
[MethodPOSTRouteadmin/permission]
in SYSTEMPATH\Validation\Validation.php on line 814.
 1 SYSTEMPATH
\Validation\Validation.php(156): CodeIgniter\Validation\Validation->fillPlaceholders([...], [...])
 
2 SYSTEMPATH\BaseModel.php(1576): CodeIgniter\Validation\Validation->run([...], nullnull)
 
3 SYSTEMPATH\BaseModel.php(808): CodeIgniter\BaseModel->validate([...])
 
4 SYSTEMPATH\Model.php(800): CodeIgniter\BaseModel->insert([...], false)
 
5 SYSTEMPATH\BaseModel.php(750): CodeIgniter\Model->insert([...], false)
 
6 APPPATH\Controllers\Users\PermissionController.php(64): CodeIgniter\BaseModel->save([...])
 
7 SYSTEMPATH\CodeIgniter.php(933): App\Controllers\Users\PermissionController->create()
 
8 SYSTEMPATH\CodeIgniter.php(507): CodeIgniter\CodeIgniter->runController(Object(App\Controllers\Users\PermissionController))
 
9 SYSTEMPATH\CodeIgniter.php(354): CodeIgniter\CodeIgniter->handleRequest(nullObject(Config\Cache), false)
10 SYSTEMPATH\Boot.php(334): CodeIgniter\CodeIgniter->run()
11 SYSTEMPATH\Boot.php(67): CodeIgniter\Boot::runCodeIgniter(Object(CodeIgniter\CodeIgniter))
12 FCPATH\index.php(56): CodeIgniter\Boot::bootWeb(Object(Config\Paths)) 
My PermissionController.php file:
PHP Code:
<?php

namespace App\Controllers\Users;

use 
App\Controllers\BaseController;
use 
App\Entities\Collection;
use 
App\Models\PermissionModel;
use 
CodeIgniter\API\ResponseTrait;

/**
 * Class PermissionController.
 */
class PermissionController extends BaseController
{
    use ResponseTrait;

    /** @var \App\Models\PermissionModel */
    protected $permission;

    /**
    * __construct.
    *
    * @return void
    */
    public function __construct()
    {
        $this->permission = new PermissionModel();
    }

    /**
    * Create a new resource object, from "posted" parameters.
    *
    * @return array an array
    */
    public function create()
    {
        if (!$data $this->permission->save($this->request->getPost())) {
            return $this->fail($this->permission->errors());
        }

        return $this->respondCreated($datalang('my_app.permission.msg.msg_insert'));
    }


My PermissionModel.php file:
PHP Code:
<?php

namespace App\Models;

use 
Myth\Auth\Models\PermissionModel as BaseModel;

class 
PermissionModel extends BaseModel
{
    const ORDERABLE = [
        1 => 'name',
        2 => 'description',
    ];


It seems to me that the problem is in the PermissionModel file from the myth-auth library, where there are such rules:
PHP Code:
    protected $validationRules = [
        'name'        => 'required|max_length[255]|is_unique[auth_permissions.name,name,{name}]',
        'description' => 'max_length[255]',
    ]; 

According to docs:
Quote:Since v4.3.5, you must set the validation rules for the placeholder field (the id field in the sample code above) for security reasons. Because attackers can send any data to your application.

I'm not sure if you can do rules this way and if this is the cause of the problem (name field in name field rules).

I made temporary something like this in my PermissionModel.php file and everything working fine, but Im not sure if this is correct way:
PHP Code:
    public function save($data): bool
    
{
        $this->validationRules = [
            'name'        => 'required|max_length[255]|is_unique[auth_permissions.name]',
            'description' => 'max_length[255]',
        ];

        return parent::save($data);
    }

    public function update($id null$data null): bool
    
{
        $this->validationRules = [
            'name'        => "required|max_length[255]|is_unique[auth_permissions.name,id,{$id}]",
            'description' => 'max_length[255]',
        ];

        return parent::update($id$data);
    

Thank you in advance for your help.

Autoroutin break after upgrade to 4.6

$
0
0
I have updatet CI on an existing installation but now the line

/**
    * If TRUE, the system will attempt to match the URI against
    * Controllers by matching each segment against folders/files
    * in APPPATH/Controllers, when a match wasn't found against
    * defined routes.
    *
    * If FALSE, will stop searching and do NO automatic routing.
    */
    public bool $autoRoute = true;

in the App->config->routing.php
don't work....

Because this is an update i need to autoconfig work

Thank you

Shield auth with sso microsoft

$
0
0
Hi there is a way to authenticate in shield with microsoft credentials ?
Viewing all 14343 articles
Browse latest View live


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