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

Codeigniter Shield control email duplicate

$
0
0
Hi there is a way to control if  user's email is present in database ? 
If i create customa validation where i can find email ? in user table is not present , in  auth_identities there is secret , but it's always email ?

Error codeigniter4/shield/src/Authentication/Authenticators/Session.php

$
0
0
Hi,

I just updated from CI 4.5.8 to CI 4.6.2 and Shield 1.1.0 to 1.2.0.

TypeError
CodeIgniter\I18n\Time::addSeconds(): Argument #1 ($seconds) must be of type int, string given, called in
/vendor/codeigniter4/shield/src/Authentication/Authenticators/Session.php on line 931

Code:
927    private function calcExpires(): Time
928    {
929        $rememberLength = setting('Auth.sessionConfig')['rememberLength'];
930
931        return Time::now()->addSeconds($rememberLength);
932    }

It appears that setting('Auth.sessionConfig')['rememberLength']; is being returned as a string.

However, my Auth config file remains unchanged from the current version on the Shield repository.

Code:
    public array $sessionConfig = [
        'field'              => 'user',
        'allowRemembering'  => true,
        'rememberCookieName' => 'remember',
        'rememberLength'    => 30 * DAY,
    ];

I have reviewed the change log for CI 4.6.2 and I can't see anything obvious that I missed updating.

Any idea?

Thanks,

Luke

CodeIgniter v4.6.3 Released - Fixing Email Mishaps

$
0
0
August 2, 2025 - The CodeIgniter development is proud to announce the release of v4.6.3, which focuses on patching recent troubles in the email service when upgrading from v4.6.1 to v4.6.2. If you are affected by this, you are advised to upgrade sooner.

This patch update also updates the PHPDoc in app/Config/Filters.php. Please update your copy accordingly.

CodeIgniter v4.6.3 Translations is also released! This patch release adds 100% translation status to the Bengali (bn) locale.

See the changelog: https://codeigniter4.github.io/userguide...4.6.3.html
Upgrading from v4.6.3: https://codeigniter4.github.io/userguide...e_463.html

Frankenphp worker mode script for CI4

$
0
0
I've been reading about the very impressive performance improvements that can be achieved with FrankenPHP as an alternative to Apache Nginx FPM.

To fully benefit from the FrankenPHP worker mode (which is where the big improvements can be achieved) it relies on running a "runtime" script that pre-loads re-usable framework resource that can be shared between requests.

Has anyone investigated what a "codeigniter runtime for frankenphp" script would look like? There already exist ones for Laraval and Symphony.

I'd be VERY interested in using frankenphp with a script optimised for CI4, but I lack the time or skills to work on one.

CodeIgniter4 DB Connection setup using .env and config/Database.php not working

$
0
0
Hello,
I'm using CodeIngiter 4 and try to connect to a database. 
I did these steps: 1) enter info in .env; 2) modified config/Database.php; 3) made a controller file to do/test the connection.
I received an error message.  I experimented with .env, Database.php, and controller file in different ways. I wasn’t successful.
The error message points to “Constant expression contains invalid operations” in config/Database.php.
 
Here is section that defines data connection parameters in the .env file:
------------------------------------------------------------.env------------------------------------------------------
 database.default.hostname = my_host_name
 database.default.database = my_database_name
 database.default.username = my_username
 database.default.password = my_password
 database.default.DBDriver = OCI8
 database.default.DBPrefix =
 database.default.port = my_port
------------------------------------------------------------------------------------------------------------------------
Here is the section that takes values from .env in config/Database.php:
------------------------------------------------------------config/Database.php-------------------------------------------
      public $default = [
          'DSN'        => '',
        'hostname' => env('database.default.hostname'),
       'username'  => env('database.default.username'),
       'password'  => env('database.default.password'),
       'database'  => env('database.default.database'),
       'DBDriver'  => env('database.default.DBDriver'),
         
       'DBPrefix'  => env('database.default.DBPrefix'),
       'port'      => env('database.default.port'),
       'charset'    => '',
       'DBCollat'   => '',
       'swapPre'    => '',
       'encrypt'    => false,
       'compress'   => false,
       'strictOn'   => false,
       'failover'   => [],
      'numberNative' => false,
        ];
----------------------------------------------------------------------------------------------------------------
Here is the controller file.
-------------------------------------------------------------------------------------------------------
namespace App\Controllers;
use CodeIgniter\Controller;
use Config\Database;
 
class Getdata extends BaseController
{
    public function index(): string
    {
      $db = \Config\Database::connect();
 
      $query = $db->query('my_query');
      $data = $query->getResult();
      return view('getdata', $data);  
   }
}
<?
}
 
------------------------------------------------------------------------------------------------------------------------
The process never executed the controller file successfully. It stopped at the config/Database.php file. The config/Database.php needs to have the constant defined, before it actually calls the values. I read online.  Do I need to define the constants in “__contruct” before using the values in config/Database.php?
Any help would be greatly appreciated!

undefined variable in vendor/codeigniter4/framework/system/Router/RouteCollection.php

$
0
0
The variable $callableName is not defined in the RouteCollection.php file. I accidentally discovered this problem while browsing this file.

Code:
private function processArrayCallableSyntax(string $from, array $to): string
{
    // [classname, method]
    // eg, [Home::class, 'index']
    if (is_callable($to, true, $callableName)) {
        // If the route has placeholders, add params automatically.
        $params = $this->getMethodParams($from);
        return '\\' . $callableName . $params;
    }
    // [[classname, method], params]
    // eg, [[Home::class, 'index'], '$1/$2']
    if (
        isset($to[0], $to[1])
        && is_callable($to[0], true, $callableName)
        && is_string($to[1])
    ) {
        $to = '\\' . $callableName . '/' . $to[1];
    }
    return $to;
}

Regards

How to update shield

$
0
0
In my project I have installed Shield using Composer.
I read the thread about new Shield version...so the questin is: how to update the installed version in my project?
I've read info and doc in github site and official site but no single word about command to update the tool.
Can I assume I have to re run the command
Code:
composer require codeigniter4/shield

Web Design vs Web Development

$
0
0
Hi everyone! 
I am currently taking a short certificate program in Web Development, which includes Web Development I & II and a Digital Arts class. During my studies, I realized one important thing:
I really enjoy designing working with Photoshop/Illustrator, creating layouts, playing with colors and typography.

I don't have a strong background in drawing or traditional graphic design, but I am willing to improve.

Has anyone here been in a similar situation? Which path did you take UI design? front-end development? UX?

Please give me some advice on this,
Thanks in advance!

Multiple filters

$
0
0
Dear all,
In one of my routes, I want to check:
1. If the user is authenticated (has a session id)
2. Check if the user completed a task (application specific filter)
So, I followed the manual (https://codeigniter4.github.io/userguide/incoming/filters.html) and made the following changes (adds) to my app\Config\Filters.php:
PHP Code:
<?php

namespace Config;

use 
CodeIgniter\Config\Filters as BaseFilters;
use 
CodeIgniter\Filters\Cors;
use 
CodeIgniter\Filters\CSRF;
use 
CodeIgniter\Filters\DebugToolbar;
use 
CodeIgniter\Filters\ForceHTTPS;
use 
CodeIgniter\Filters\Honeypot;
use 
CodeIgniter\Filters\InvalidChars;
use 
CodeIgniter\Filters\PageCache;
use 
CodeIgniter\Filters\PerformanceMetrics;
use 
CodeIgniter\Filters\SecureHeaders;

// Custom => Added
use App\Filters\AuthFilter;
use 
App\Filters\LockFilter;


class 
Filters extends BaseFilters
{

    public array $aliases = [
        'csrf'          => CSRF::class,
        'toolbar'      => DebugToolbar::class,
        'honeypot'      => Honeypot::class,
        'invalidchars'  => InvalidChars::class,
        'secureheaders' => SecureHeaders::class,
        'cors'          => Cors::class,
        'forcehttps'    => ForceHTTPS::class,
        'pagecache'    => PageCache::class,
        'performance'  => PerformanceMetrics::class,

        // Custom => Added
      'check-locked' => [
            AuthFilter::class,
            LockFilter::class,
        ],
     ]; 

The first part in the combination (AuthFilter) returns true if authenticated and sends the user to a login page if not (works correct).
But after authentication check, it seems that the second part, the LockFilter is not executed! (I checked with 'dd' and 'die()' statements... and putting the first - AuthFilter - into comment).
On the earlier mentionned manual page, I read that the paragraph: 'Stopping Later Filters' argues that execution of later filters can be stopped after a certain filter by returning an NON-EMPTY result. 
Because I'm returning true, the second filter is probably stopped. But if I don't return true, the first (AuthFilter) keeps on checking for a sassion id ans causing multiple redirects.

Any help or suggestions are very welcome!
Many thanks in advance, 
Zeff

phpunit - turn off Database tests?

$
0
0
Hi all,
I don't have an issue now, but today had an issue using phpunit.  Making this post for general discussion to whoever may be interested. It could be I was doing something wrong, or it could be an issue ?
Code:
PHP 8.3
CI 4.6.3
PHPUnit 12.3
========================================================

Just created a new CI4 project. Running phpunit with some simple tests (no DB involved) generated errors like-:
Code:
3) ExampleDatabaseTest::testSoftDeleteLeavesRow
CodeIgniter\Database\Exceptions\DatabaseException: Unable to connect to the database.
Main connection [SQLite3]: Class "SQLite3" not found

/home/dev/src/php/scraper/vendor/codeigniter4/framework/system/Database/BaseConnection.php:465
/home/dev/src/php/scraper/vendor/codeigniter4/framework/system/Database/SQLite3/Connection.php:74
/home/dev/src/php/scraper/vendor/codeigniter4/framework/system/Test/DatabaseTestTrait.php:83
/home/dev/src/php/scraper/vendor/codeigniter4/framework/system/Test/DatabaseTestTrait.php:59
/home/dev/src/php/scraper/vendor/codeigniter4/framework/system/Test/CIUnitTestCase.php:251

Fixed this by deleting the tests/database directory. 
========================================================
Also, just pointing this out, in phpunit.xml.dist-:
Code:
    xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.5/phpunit.xsd"
When phpunit 12 generated  phpunit.xml file contains-:
Code:
        xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"



Many thanks, any responses welcome.
Mike

The Art of Talking to AI: Prompts That Actually Work for Coding

7 Git Commands You Probably Don’t Know (But Should)

TypeError: fwrite(): supplied resource is not a valid stream resource

$
0
0
Hi there, I am new to CodeIgniter and Shield. After installing the frameworks and while testing them, I encountered a TypeError in the Shield addon,  as shown below. How do I fix this? I have done no customization to Shield.

TypeError
fwrite(): supplied resource is not a valid stream resource

SYSTEMPATH\Email\Email.php at line 2084
Code:
2077    protected function sendData($data)
2078    {
2079        $data .= $this->newline;
2080
2081        $result = null;
2082
2083        for ($written = $timestamp = 0, $length = static::strlen($data); $written < $length; $written += $result) {
2084            if (($result = fwrite($this->SMTPConnect, static::substr($data, $written))) === false) {
2085                break;
2086            }
2087
2088            // See https://bugs.php.net/bug.php?id=39598 and http://php.net/manual/en/function.fwrite.php#96951
2089            if ($result === 0) {
2090                if ($timestamp === 0) {
2091                    $timestamp = Time::now()->getTimestamp();
SYSTEMPATH\Email\Email.php : 2084   —   fwrite()SYSTEMPATH\Email\Email.php : 1993   —  CodeIgniter\Email\Email->sendData ( arguments )
1986
1987            case 'reset':
1988                $this->sendData('RSET');
1989                $resp = 250;
1990                break;
1991
1992            case 'quit':
1993                $this->sendData('QUIT');
1994                $resp = 221;
1995                break;
1996
1997            default:
1998                $resp = null;
1999        }
2000 SYSTEMPATH\Email\Email.php : 2232   —  CodeIgniter\Email\Email->sendCommand ( arguments )
2225        return ! empty($mime) ? $mime : 'application/x-unknown-content-type';
2226    }
2227
2228    public function __destruct()
2229    {
2230        if ($this->SMTPConnect !== null) {
2231            try {
2232                $this->sendCommand('quit');
2233            } catch (ErrorException $e) {
2234                $protocol = $this->getProtocol();
2235                $method  = 'sendWith' . ucfirst($protocol);
2236                log_message('error', 'Email: ' . $method . ' throwed ' . $e);
2237            }
2238        }
2239    }{PHP internal code}   —  CodeIgniter\Email\Email->__destruct ()

CI 4.3.3 download displayed in browser instead of saving ?

$
0
0
I am using CI 4.3 that for technical reasons cannot be upgraded to 4.6 right now.
We do need to add a function that opens a file download directly in the browser for viewing instead of opening the "save" dialog.
The problem I have is that CI 4.3 lacks the $this->response->download(xxx)->inline() method of CI 4.6.
I tried using setHeader('Content-Disposition', 'inline') and several solutions that I found on this forum. Regardless of what I tried,
$this->response->download(xxx) seems to always override any attempt to tweak the 'Content-Disposition' header by setting it to 'attachment' again.
Here is an example: Neither 'Content-Type' nor 'Content-Disposition' are set:
$response = $this->response->download($filepath, null)->setFileName($orgfilename);
$response->setContentType($mimetype);
$response->setHeader('Content-Disposition', 'inline');
$response->send();

Model insert and upload file not work

$
0
0
Hello everyone. Sorry for my English and my CI knowledge!
There was a problem loading the file.
The situation is this: if I do a file upload before the insert, namely, I write this line
Code:
$torrFile = $this->request->getFile('torrentfile');
$torrName = $torrFile->getRandomName();
---->>>>>$torrPath = $torrFile->store(setting('Torrent.TorrentUploadPath'), $torrName);
Then the insert does not happen, nothing happens, there is no error!
And it doesn’t matter what I write when saving the file: store or move. If you comment out only this line, the insert works fine! 
Tried on different UserModel models from Codeigniter Shield and my model. The behavior is the same!
Tell me where to look?

Auto Routing and Validation

$
0
0
Hello everyone,

I'm currently migrating my project to the latest version of Code Igniter and I noticed that i have used in the past often the same methode inside a Controller for post and get methods which makes it a bit tricky to migrate easily when using Auto Routing. Some ideas came into my mind how to solve this like defining a
1) postCreate method that is calling internally getCreate method,
2) defining manual routs for those methods
3) any better idea

But I wasn't in the end sure if this is really a good idea in the end. Or if a clean separation is the better way to go.
In most cases I'm using the Validation Library in those scenarios. I tried to look for this also inside the forum but haven't found anything fitting. So maybe you can help me out with some best practice for this scenario. Thanks in advance.

i want to use custom controller in codeigniter/shield

$
0
0
In codeigniter sheild docs already mention that how to customize, it becomes hard to customize custom urls and controllers for auth. How can i customize? Can someone suggest example?

$response->getJSON(true) delivers string instead of array

$
0
0
Hi, i have an app developed in CI 4.6, inside i use 
$client = \Config\Services::curlrequest([
    'baseURI' => $this->ApiBaseURL,
    'timeout' => 30,
]);
$response = $client->get('document/' . $docId, [
    'auth' => [ $this->ApiUser, $this->ApiUserPassword ],
    'http_errors' => false,
]);

$data = $response->getJSON(true);
for some reason that won't work, becaue getJSON delivers an array consisting of a string of the JSON send by the endpoint.
Code:
"{\n    \"id\": \"umkuxfvo5pvta8ocz\",\n    \"file_exist\": true,\n}\n"
I've tried with curl and verified my endpoint works correct.
I've also checked the response headers for "application/json" in the $response object.

In an old stackoverflow somebody mentioned that this could be a bug in an early 4.x release of CI: https://stackoverflow.com/questions/7767...hatgpt.com

Pager config in modules

$
0
0
In my project I'm adding a module for Admin login and functions.
Following what the official guide says I've added a Config folder in module; I've added a Routes config file and it works.
Now I'm trying to add a Pager config file...but it seems to me that it doesn't work as expected.
Of course I've edited the namespace, so the Pager file looks like the following one...since the module namespace is Acme\Admin\Config.
I know there is another thread in the forum talking abour Registrar...but I'm wondering if there is a way to use Pager config in module...according to what even Dave Hollingworth says in his Codeigniter course...but with no details about how it should work.
Thanks a lot for any hint or suggestions. 
Code:
<?php

namespace Acme\Admin\Config;

use CodeIgniter\Config\BaseConfig;

class Pager extends BaseConfig
{
    /**
    * --------------------------------------------------------------------------
    * Templates
    * --------------------------------------------------------------------------
    *
    * Pagination links are rendered out using views to configure their
    * appearance. This array contains aliases and the view names to
    * use when rendering the links.
    *
    * Within each view, the Pager object will be available as $pager,
    * and the desired group as $pagerGroup;
    *
    * @var array<string, string>
    */
    public array $templates = [
        'default_full'  => 'Acme\Admin\Views\pagers\admingavs_full',
        //'default_full'  => 'CodeIgniter\Pager\Views\default_full',
        'default_simple' => 'CodeIgniter\Pager\Views\default_simple',
        'default_head'  => 'CodeIgniter\Pager\Views\default_head',
        'gavs_full'      => 'App\Views\Pagers\gavs_full',
    ];

    /**
    * --------------------------------------------------------------------------
    * Items Per Page
    * --------------------------------------------------------------------------
    *
    * The default number of results shown in a single page.
    */
    public int $perPage = 20;
}

Shield Registrar

$
0
0
I'm trying to figure out how Registrar works...I've installed Shield in my project and created an Admin Module.
In module's Config Folder I've created a Registrar file to add a custom filter...below the code of the Registrar file.
An issue arised when trying to login using Shield login function...I get an error saying the code in the screenshot below.
I have no idea what the error is or how to fix it...any hint? I can only says that the error disappear and login works fine as soon as I delete the Registrar file
Thanks a lot for any help
[Image: shield_error.png]

Code:
<?php

namespace CodeIgniter\Shield\Config;

use CodeIgniter\Shield\Filters\SessionAuth;
use CodeIgniter\Shield\Filters\TokenAuth;

class Registrar
{
    /**
    * Registers the Shield filters.
    */
    public static function Filters(): array
    {
        return [
            'aliases' => [
                'session' => SessionAuth::class,
                'tokens'  => TokenAuth::class,
                'admin'  => \Acme\Admin\Filters\AdminFilter::class,
            ],
        ];
    }
   
    public static function Pager(): array
    {
        return [
            'templates' => [
                'module_pager' => 'Acme\Admin\Views\pagers\admingavs_full',
            ],
        ];
    }
}
Viewing all 14346 articles
Browse latest View live


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